撒科打诨
我不会帮你完成家务。但是我会引导你思考你的这个例子将走向何方。这是快速排序的第一步 - 对数组进行分区。public class QuickSortImpl { private static void swap(int[] array, int l, int h) { int temp = array[h]; array[h] = array[l]; array[l] = temp; } public static int partition(int[] array, int low, int high) { int pivot = high; int firsthigh = low; int x,y; for (int i = low; i < high; i++) { x = array[i]; y = array[pivot]; if (array[i] < array[pivot]) { swap(array, i, firsthigh); firsthigh++; } } swap(array, pivot, firsthigh); return firsthigh; } private static void printArray(int[] arr ) { for ( int i =0; i < arr.length; i++ ) { System.out.print(" " + arr[i]); } System.out.println(); } public static void quickSort(int[] array, int low, int high) { if ( low < high ) { int pivot = partition(array, low, high); quickSort(array, low, pivot - 1); quickSort(array, pivot + 1, high); } } public static void main(String[] args) { int[] arr = { 3, 22, 1, 5, 6, 10, 4}; quickSort(arr, 0, arr.length -1 ); printArray(arr); }}
哆啦的时光机
看看这个简单的例子:public static void main(String[] args) { Integer[] listOfNumbers = {1,4,5,6,74,2,7,8,5,2,6,989,3}; //sort by number 6 FirstCustomComparator comparator = new FirstCustomComparator(6); Arrays.sort(listOfNumbers, 0, listOfNumbers.length, comparator); for (int number : listOfNumbers) { System.out.print(number+" "); } }第一定制比较器类:public class FirstCustomComparator implements Comparator<Integer> { private final int exception; public FirstCustomComparator(int i) { exception = i; } @Override public int compare(Integer a, Integer b) { if (a < exception) { return -1; } return a.compareTo(b); }}