java写的快速排序 记录下。。

Description of quicksortQuicksort, like merge sort, is based on the divide-and-conquer paradigm introduced in Section 1.3.1. Here is the three-step divide-and-conquer process for sorting a typical subarray A[p . . r]. To sort an entire array A, the initial call is QUICKSORT(A, 1, length[A]). The key to the algorithm is the PARTITION procedure, which rearranges the subarray A[p . . r] in place.

以下是java代码:

public class quickSort {
        void qs(int[] a,int q,int r){
            int i=q,j=r,x,temp;
            x=a[q];
            if(q>=r) return;
            while(true){
                while(a[i]<x) i++;
                while(a[j]>x) j--;
                if(i<j){
                    temp=a[i];a[i]=a[j];a[j]=temp;
                    j--;
                    i++;
                }
                else break;
            }
            qs(a,q,j);
            qs(a,j+1,r);
        }
        public static void main(String argvs[]){
            quickSort q=new quickSort();
            int a[]={5,3,2,6,4,1,3,7};
            q.qs(a,0,a.length);
            for(int i=0;i<8;i++)
                System.out.print(a[i]+" ");
        }
}

 

Divide: The array A[p . . r] is partitioned (rearranged) into two nonempty subarrays A[p . . q] and A[q + 1 . . r] such that each element of A[p . . q] is less than or equal to each element of A[q + 1 . . r]. The index q is computed as part of this partitioning procedure.

Conquer: The two subarrays A[p . . q] and A[q + 1 . . r] are sorted by recursive calls to quicksort.

Combine: Since the subarrays are sorted in place, no work is needed to combine them: the entire array A[p . . r] is now sorted.

The following procedure implements quicksort.

 

QUICKSORT(A,p,r)

 

1  if p < r

 

2      then q = PARTITION(A,p,r)

 

3           QUICKSORT(A,p,q)

 

4           QUICKSORT(A,q + 1,r)

 

 

Partitioning the array

 

 

PARTITION(A,p,r)

 

1  x =A[p]

 

2  i = p - 1

 

3  j = r + 1

 

4  while TRUE

 

5      do repeat j = j - 1

 

6           until A[j] <= x

 

7         repeat i = i + 1

 

8           until A[i] >= x

 

9         if i < j

 

10            then exchange A[i] and A[j]

 

11            else return j
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值