快速排序 及 java实现

描述:通过一趟排序将待排记录分割成独立的两部分,其中一部分记录的关键字均比另一部分记录的关键字小

过程:

     分解:数组A[p…r]被划分成两个(可能为空)子数组A[p..q-1]和A[q+1..r],使得A[p ..q-1] <= A[q] <= A[q+1 ..r]

     解决:递归调用对子数组A[p..q-1]和A[q+1…r]排序

     合并:合并数组

时间复杂度:O(n * log n)

伪代码:

QUICKSORT(A,p,r)

    if p<r

       then q = PARITION(A,p,r)

            QUICKSORT(A,p,q-1)

            QUICKSORT(A,q+1,r)

排序完整数组最初调用 QUICKSORT(A,1,lenght[A])

 

  PARITION(A,p,r)

     x=A[r]

     i=p-1

     for(j=p to r-1)

        do if(A[j]<=x)

           then i = i+1

                exchange A[i] = A[j]

     exchange A[i+1] = A[r]

     return i+1  

代码实现:

 

 1        /*快速排序*/
 2 
 3     private static void Qsort(int[] a,int low,int high){
 4 
 5        if(low < high){
 6 
 7            int pivotloc = quickSort(a,low, high);
 8 
 9            Qsort(a,low, pivotloc-1);
10 
11            Qsort(a, pivotloc+1, high);
12 
13        }
14 
15     }
16 
17    
18 
19     private static int quickSort(int []a,int low,int high){
20 
21        int x = a[high];
22 
23        int i = low - 1;
24 
25        for(int j = low;j<=high-1;j++){
26 
27            if(a[j]<=x){
28 
29               i = i+1;
30 
31               exchange(i,j);
32 
33            }
34 
35        }
36 
37        exchange(i+1,high);
38 
39        System.out.println("第"+time+"次排序结果");
40 
41        time++;
42 
43        for(int index=0;index<a.length;index++){
44 
45            System.out.print(a[index]+" ");
46 
47            }
48 
49        System.out.println("");
50 
51        return i+1;
52 
53         }
相信一万小时定律,我没天赋,但我能用努力和坚持来弥补
原文地址:https://www.cnblogs.com/breeze1988/p/2851077.html