- 快速排序代码(注释见下):
-
选第一个元素作为 基准(
pivot
) -
重新排序(从小到大),所有比基准值小的元素放在基准前面,所有比基准值大的元素放在基准的后面(先从后往前找第一个比基准小的元素,交换,再从前往后找第一个比基准大的数,交换)。结束之后,基准就处于数组的中间位置,这个称为分区(
partition
)操作public class Main { void quickSort(int[] a, int low, int high){ if(low < high){ int pivot = partition(a, low, high); quickSort(a, low, pivot - 1); quickSort(a, pivot + 1, high); } } int partition(int[] a, int low, int high){ int pivot = a[low]; while(low < high){ while(low < high && a[high] >= pivot){ high--; } a[low] = a[high]; while(low < high && a[low] <= pivot){ low++; } a[high] = a[low]; } a[low] = pivot; return low; } }
- 测试用例:
public class Main {
public static void main(String[] args) {
int[] a = {8,4,5,7,1,3,6,2};
quickSort(a, 0, a.length - 1);
for(int i = 0; i < a.length; i++){
System.out.print(a[i] + " ");
}
//System.out.println(Arrays.toString(a));
//Arrays.toString()方法是方便数组类型输出,不用使用for遍历数组
}
static void quickSort(int[] a, int low, int high){
if(low < high){
int pivot = partition(a, low, high);
quickSort(a, low, pivot - 1);
quickSort(a, pivot + 1, high);
}
}
static int partition(int[] a, int low, int high){
//第一个元素为基准元素
int pivot = a[low];
while(low < high){
//从后往前找第一个比基准小的元素
while(low < high && a[high] >= pivot){
high--;
}
//把比基准小的数移到低端
a[low] = a[high];
//再从前往后找第一个比基准大的数
while(low < high && a[low] <= pivot){
low++;
}
//把比基准大的数据移到高端
a[high] = a[low];
}
a[low] = pivot;// 将基准值插入到首部和尾部中间位置,注意此时的low不是起始位置,而是已经走到了中间位置
return low;// 返回基准值的位置
}
}
输出结果
(1)Arrays.toString(a)
输出结果:
(2)for
循环输出结果: