1. 程式人生 > >java算法----排序----(4)快速排序

java算法----排序----(4)快速排序

sort pre alt () ram pack image ret println

 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 }

下面這事控制臺的輸出

技術分享圖片

java算法----排序----(4)快速排序