剑指offer中的快排

一、快速排序的思想。
每一次的快排,都是选定一个坐标,把一个数组分隔成两部分。一边是比坐标的数大的数,一边是比坐标的数小的数。
之后把分隔的两个部分在各自选取一个坐标,在分别进行分隔。直到分隔的区间只剩一个数为止。
习惯上把标志位的数放在数组的最后一位上,这样方便进行比较。
这里写图片描述
快排的一部分过程
二、快速排序的代码。
public class QuickSort {
int [] array = null;
int length = 0;

public QuickSort(int [] array) {
    this.array = array;
    this.length = array.length;
}
private void Swap (int i,int j){
    int temp;
    temp = array[i];
    array[i] = array[j];
    array[j] = temp;
}

private int RandomSubscript(int start,int end){
    int index = (int)(Math.random()*(end-start+1)+start);
    return index;
}

private int partition(int start,int end){
    int small = -1;
    int index = RandomSubscript(start, end);
    Swap(index , end);
    small = start-1;
    for(index = start ; index < end ; index++){
        if(array[index] < array[end]){
            ++small;
            if(small != index){
                Swap(small, index);
            }
        }
    }
    ++small;
    Swap(small,end);
    return small;

}

public void printSqrt(){
    for(int i = 0 ; i < array.length ; i++){
        System.out.print(array[i]+"  ");
    }
    System.out.println();
}

public void quickSqrt(int start,int end){
    if(array ==null||array.length<=0){
        System.out.println("数组不合法,无法进行排序");
        return;
    }
    if(start<end){
        int index = partition(start,end);
        if(index > start){
            quickSqrt(start,index-1);
        }
        if(index < end){
            quickSqrt(index+1,end);
        }
    }
    return ;
}

}
代码详解:
small是用来卡主比选中的小的数,将比选中的数小的数放在左边,大的数放在右边。small所在的位置是当前最近的比标志数小的数,small之前(包括small)都是比标志数小的数,之后的数都是不确定的。在跳出循环后,small之前(包括)之前的都是比标志位小的,small之后(除了标志位)都是比标志位大的。所以跳出循环后只需要把标志位和samll后面的一个数一交换就可以了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值