标签:
通过设置一个岗哨,每次跟这个岗哨进行比较,比他小的放在左边,比他大的放在右边。再对岗哨左边的数组0----middle-1,和middle+1-----end,进行同样的排序。
快速排序时间复杂度为O(nlogn),由于是在原数组上面利用替换来实现,因此不需要额外的存储空间。
1 public static void quickSort(int []a,int low,int high){ 2 int middle; 3 if(low<high){ 4 middle = Partition(a,low,high); 5 quickSort(a,low,middle-1); 6 quickSort(a,middle+1,high); 7 } 8 } 9 public static int Partition(int []arr,int low,int high){ 10 int middle = arr[low]; 11 int tmp; 12 while(low<high){ 13 while(low<high && arr[high]>=middle) 14 high--; 15 tmp = arr[high]; 16 arr[high]= arr[low]; 17 arr[low]=tmp; 18 while(low<high && arr[low]<=middle) 19 low++; 20 tmp = arr[high]; 21 arr[high]= arr[low]; 22 arr[low]=tmp; 23 } 24 return low; 25 }
1 package quickSort; 2 //通过设置一个岗哨,每次跟这个岗哨进行比较,比他小的放在左边,比他大的放在右边。 3 //再对岗哨左边的数组0----middle-1,和middle+1-----end,进行同样的排序。 4 public class Sort { 5 static int arrtest1[] = {4,3,7,8,0,9,1,2,6,5}; 6 int arrtest2[] = {0,1,2,3,4,5,6,7,8,9}; 7 int arrtest3[] = {9,8,7,6,5,4,3,2,1,0}; 8 public static void main(String args[]){ 9 display(arrtest1); 10 quickSort(arrtest1,0,arrtest1.length-1); 11 display(arrtest1); 12 } 13 public static void quickSort(int []a,int low,int high){ 14 int middle; 15 if(low<high){ 16 middle = Partition(a,low,high); 17 quickSort(a,low,middle-1); 18 quickSort(a,middle+1,high); 19 } 20 } 21 public static int Partition(int []arr,int low,int high){ 22 int middle = arr[low]; 23 int tmp; 24 while(low<high){ 25 while(low<high && arr[high]>=middle) 26 high--; 27 tmp = arr[high]; 28 arr[high]= arr[low]; 29 arr[low]=tmp; 30 while(low<high && arr[low]<=middle) 31 low++; 32 tmp = arr[high]; 33 arr[high]= arr[low]; 34 arr[low]=tmp; 35 } 36 return low; 37 } 38 public static void display(int[]a){ 39 for(int i=0;i<a.length;i++){ 40 System.out.print(a[i]+" "); 41 } 42 System.out.println(); 43 } 44 }
运行结果
标签:
原文地址:http://www.cnblogs.com/doudingbest/p/4477576.html