QuickSort

Quicksort, or partition-exchange sort, is a sorting algorithm that, on average, makes O(n log n) comparisons to sort n items. In the worst case, it makes O(n2) comparisons, though this behavior is rare. Quicksort is often faster in practice than other O(n log n) algorithms.

 1 /*
 2  * Best     Average    Worst     Memory   Stable
 3  * nlogn     nlogn     n^2       logn       No
 4 */
 5 public class QuickSort {
 6         
 7     public static void sort(int[] a,int from,int to){
 8         if(from<to){
 9             int mid=a[to];
10             int i=from-1;
11             for(int j=from;j<to;j++){
12                 if(a[j]<=mid){
13                     i++;
14                     int temp=a[j];
15                     a[j]=a[i];
16                     a[i]=temp;
17                 }
18             }
19             a[to]=a[i+1];
20             a[i+1]=mid;
21             sort(a,from,i);
22             sort(a,i+1,to);
23         }
24     }
25     
26     public static void printArray(int[] a){
27         for(int i = 0;i < a.length;i++){
28             System.out.print(a[i]+" ");
29         }
30     }
31     
32     public static void main(String[] args) {
33         // TODO Auto-generated method stub
34          int[] a={ 2, 0 ,1,5,5, 4, 9, 8, 6, 7, 10, 3 }; 
35          sort(a,0,a.length -1);
36          printArray(a);
37     }
38 
39 }

 

Additionally, quicksort's sequential and localized memory references work well with a cache. Quicksort is a comparison sort and, in efficient implementations, is not a stable sort. Quicksort can be implemented with an in-place partitioning algorithm, so the entire sort can be done with only O(log n) additional space used by the stack during the recursion.

posted on 2013-03-30 19:23  melotang  阅读(156)  评论(0)    收藏  举报