快速排序是C.R.A.Hoare于1962年提出的一种划分交换排序。它采用了一种分治的策略,通常称其为分治法(Divide-and-ConquerMethod)。
该方法的基本思想是:
1.先从数列中取出一个数作为基准数(pivot)。
2.分区过程,将比这个数大的数全放到它的右边,小于或等于它的数全放到它的左边。
3.再对左右区间重复第二步,直到各区间只有一个数。
java类QuickSort:
1 class QuickSort { 2 public void sort(int left, int right, int arr[]) { 3 // get the first as the pivot 4 int pivot = arr[left]; 5 int l = left; 6 int r = right; 7 if (l < r) { 8 while (l < r) { 9 // find one which is less than or equals to the pivot 10 while (l < r && arr[r] > pivot) 11 r--; 12 // place it in where there is a blank,then l++ 13 if (r > l) 14 arr[l++] = arr[r]; 15 // find one which is greater than the pivot 16 while (l < r && arr[l] <= pivot) 17 l++; 18 // place it in where there is a blank,then r-- 19 if (r > l) 20 arr[r--] = arr[l]; 21 } 22 // ended in the condition of l==r 23 arr[l] = pivot;// l==r and arr[l]==arr[r] now is meanningless 24 // (blank) 25 if (left < l - 1) 26 sort(left, l - 1, arr); 27 if (right > l + 1) 28 sort(l + 1, right, arr); 29 } 30 } 31 32 } 33 34 public class Demo1 { 35 36 /** 37 * @param args 38 */ 39 public static void main(String[] args) { 40 int len = 8000000; 41 int arr[] = new int[len]; 42 int k = 0; 43 while (k < len) { 44 arr[k] = (int) (Math.random() * 10000); 45 k++; 46 } 47 // int arr[]={1,8,921,15,90,45,3,89,7}; 48 QuickSort qs = new QuickSort(); 49 Calendar cal = Calendar.getInstance(); 50 System.out.println("sort start:" + cal.getTime()); 51 qs.sort(0, arr.length - 1, arr); 52 cal = Calendar.getInstance(); 53 System.out.println("sort ended:" + cal.getTime()); 54 /* 55 * for(int i=0;i<arr.length;i++) { System.out.println(arr[i]); } 56 */ 57 } 58 }