java算法----排序----(4)快速排序
1 package log; 2 3 public class Test4 { 4 5 /** 6 * java算法---快速排序 7 * 8 * @param args 9 */ 10 public static void main(String[] args) { 11 // 需要排序的数组 12 int arr[] = { 49, 20, 36, 51, 18, 94, 61, 31, 50 }; 13 // 循环输出该数组内容 14 System.out.println("排序之前:"); 15 for (int a : arr) { 16 System.out.print(a + "\t"); 17 } 18 System.out.println(); 19 20 if (arr.length > 0) { 21 sort(arr, 0, arr.length - 1); 22 } 23 // 循环输出该数组内容 24 System.out.println("排序之后:"); 25 for (int a : arr) { 26 System.out.print(a + "\t"); 27 } 28 System.out.println(); 29 30 } 31 32 public static int getMiddle(int[] list, int low, int high) { 33 int temp = list[low]; 34 while (low < high) { 35 while (low < high && list[high] >= temp) { 36 high--; 37 } 38 list[low] = list[high]; 39 while (low < high && list[low] <= temp) { 40 low++; 41 } 42 list[high] = list[low]; 43 } 44 list[low] = temp; 45 return low; 46 } 47 48 public static void sort(int[] list, int low, int high) { 49 if (low < high) { 50 int middle = getMiddle(list, low, high); 51 sort(list, low, middle - 1); 52 sort(list, middle + 1, high); 53 } 54 } 55 56 }
下面这事控制台的输出
llh