同事写的快排算法

package Sort;


/**
 * 快速排序 1.当前数组拿到第一个数作为标准
 *  2.从前往后,从后往前,两个指针扫相对着往后扫描 当左往右的大于标准,右往左的小于标准,交换当右指针索引小于左指针,将当前右指针指向的数和标准进行交换 
 * 3.当前标准找到了正确位置,其他的数划分成两个子数组递归排序
 * 
 * 例
 * 第一次交换 27 99(i) 0 8 13 64 86 16 7 10 88 25(j) 90
 * 第二次交换 27 25 0 8 13 64(i) 8616 7 10(j) 88 99 90 
 * 第三次交换 27 25 0 8 13 10 86(i) 16 7(j) 64 88 99 90 
 * 第四次交换 27 25 0 8 13 10 7 16(j) 86(i) 64 88 99 90 
 * 划分 16 25 0 8 13 10 7 27 86 64 88 99 90
 * 
 * @author lucky-freya
 *
 */




public class QuickSort {


public int partition(int[]array,int startIndex,int endIndex){
int x = array[startIndex];
int i = startIndex + 1;
int j = endIndex;

while(true){

//判断指针移位
while(i<= endIndex && array[i] <= x){
i++;
}
while(j>=0 && array[j]>x){
j--;
}

   // 交换
if(i<j){
int swap = array[i];
array[i] = array[j];
array[j] = swap;
}else{
return j;
}
}
}

public void quickSort(int[]array,int startIndex,int endIndex){

if (startIndex >= endIndex){
return;
}

int index = partition(array,startIndex,endIndex);

//交换
int swap = array[startIndex];
array[startIndex] = array[index];
array[index] = swap;

quickSort(array,startIndex,index - 1);
quickSort(array,index + 1,endIndex);
}

public static void main(String args){

QuickSort  sort = new QuickSort();

int[] array = new int[]{27,99,0,8,13,64,86,16,7,10,29,299};

sort.quickSort(array, 0, 11);
for(int i = 0;i<array.length;i++){
System.out.println(array[i]);
}
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值