快速排序-java实现

public class quickSort1 {
public static void main(String[] args) {
int[] num = {5, 23, -1, 3, 6, 4, 8, 1};
new quickSort1().sort(num,0, num.length-1);
for (int i = 0; i < num.length; i++) {
System.out.print(num[i] + " ");
}
}
public void sort(int[]num,int left, int right) {
if (left > right)
return;
/*取数组的第一个值为基准*/
int partition = num[left];
int start = left;
int end = right;
/*定义两个指针,分别从数组的两端开始移动*/
while (start!=end) {
/*右端指针先走,直到找到小于基准的值*/
while (start < end && num[end] >= partition) {
end--;
}
/*左端指针后走,直到找到大于基准的值*/
while (start < end && num[start] <= partition) {
start++;
}
/*当左右指针还未相遇时就找到了目标,则交换位置*/
if (start < end) {
int i = num[start];
num[start] = num[end];
num[end] = i;
}
}
//此时的left和right指针走到了一起
//把基准数与该点交换位置
num[left]=num[start];
num[start]=partition;
/*通过基准将数组分为两部分,继续排序*/
sort(num,left, start - 1);
sort(num,start + 1, right);
}

}

猜你喜欢

转载自www.cnblogs.com/yfy-/p/10508119.html