1.冒泡,选择排序
public class TestA { public static void main(String[] args) { int[] arr = new int[args.length]; for(int i=0;i=1;i--) { for(int j=0;j arr[j+1]) { tmp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = tmp; } } } } //这一个依次和其他对比交换 public static void selectSort(int[] arr){ int k,tmp; for(int i=0;i arr[j]) { k = j; } } if(k != i) { tmp = arr[i]; arr[i] = arr[k]; arr[k] = tmp; } } } public static void print(int[] arr) { for(int i=0;i
2.二分法查找
public class TestSearch { public static void main(String[] args) { int a[] = { 1, 3, 6, 8, 9, 10, 12, 18, 20, 34 }; int i = 12; //System.out.println(search(a, i)); System.out.println(binarySearch(a, i)); } public static int search(int[] a, int num) { for(int i=0; ia[m]) { startPos = m + 1; } if(num < a[m]) { endPos = m -1; } m = (startPos + endPos) / 2; } return -1; }}
3.
/** * 500个小孩围成一圈,每数到3则推出,继续数,计算最后那个小孩的位置 */public class count3Quit { public static void main(String[] args) { boolean[] arr = new boolean[500]; for(int i=0;i1) { if(arr[index] == true) { countNum ++; if(countNum == 3) { countNum = 0; arr[index] = false; leftCount --; } } //保证数组一直循环下去 index ++; if(index == arr.length) { index = 0; } } //找出最后元素的位置 for(int i=0;i
4.上面的问题,用面向对象的方式实现
//500个小孩围成一圈,每数到3则推出,继续数,计算最后那个小孩的位置public class count3Quit { public static void main(String[] args) { KidCircle kc = new KidCircle(10); kc.print(); /*int countNum = 0; Kid k = kc.first; while(kc.count > 1) { countNum ++; if(countNum == 3) { countNum = 0; kc.delete(k); } k = k.right; } //这时只剩一个元素 System.out.println(kc.first.id);*/ }}class Kid { int id; Kid left; Kid right;}class KidCircle { int count = 0; Kid first, last; KidCircle(int n) { for(int i=0; i