快速排序的思路如下:在待排序的数组中选择一个称为主元的元素,将数组分为两部分,使得前半部分中的所有元素都小于或等于主元,而后半部分中的所有元素都大于主元。然后分别对这两部分递归地应用此思路进行排序。
public class QuickSort {
public static void sort(int[] list) {
sort(list, 0, list.length - 1);
}
public static void sort(int[] list, int first, int last) {
if(last > first) {
// 1.确定主元位置
int pivotIndex = partition(list, first, last);
// 2.对小于主元的那一部分元素递归排序
sort(list, first, pivotIndex - 1);
// 3.对大于主元的那一部分元素递归排序
sort(list, pivotIndex + 1, last);
}
}
private static int partition(int[] list, int first, int last) {
int pivot = list[first]; //选择第一个元素作为主元
int low = first + 1; //从左往右遍历的索引
int high = last; // 从右往左遍历的索引
while(high > low) {
//从左边向右边找到第一个大于主元的元素索引
while(low <= high && list[low] <= pivot) {
low++;
}
//从右边向左边找到第一个小于主元的元素索引
while(low <= high && list[high] >= pivot) {
high--;
}
//如果此时索引没有发生交叉,即左边有一个数比主元大,右边有一个数比主元小,便交换这两个数
if(low < high) {
int temp = list[low];
list[low] = list[high];
list[high] = temp;
}
}
//确定主元将插入位置的索引
while(high > first && list[high] >= pivot) {
high--;
}
//返回主元的位置
if(pivot > list[high]) {//主元需要移动位置,主元将数组划分为两个子数组的情况
list[first] = list[high];
list[high] = pivot;
return high;
}else {//主元不需要移动,剩余的元素全部小于(大于)主元的情况
return first;
}
}
public static void main(String[] args) {
int[] num = {2,4,6,5,3,7,8,1};
sort(num);
for(int i : num) {
System.out.print(i+" ");
}
}
}
1067

被折叠的 条评论
为什么被折叠?



