原理逻辑
同冒泡排序一样,快速排序也属于交换排序,通过元素之间的比较和交换位置来达到排序的目的。
不同的是,冒泡排序在每一轮只把一个元素冒泡到数列的一端,而快速排序在每一轮挑选一个基准元素,并让其他比它大的元素移动到数列一边,比它小的元素移动到数列的另一边,从而把数列拆解成了两个部分。
注:快速排序属于不稳定排序。
Java代码实现
/**
* <快速排序>
*
* @Author: chenxin
* @Date: 2020/9/11
*/
public class Main {
public static void main(String[] args) {
List<Integer> list = Arrays.asList(3, 2, 1, 4, 6, 9, 4, 3, 5);
List<Integer> sortedList = new SortUtil().quickSort(list);
System.out.println("list = " + list);
System.out.println("sortedList = " + sortedList);
}
}
class SortUtil {
/**
* 功能描述: 将list排序后 返回
*
* @Author: chenxin
* @Param: [list]
* @Date: 2020/9/11
*/
public List<Integer> quickSort(List<Integer> list) {
Integer[] nums = list.toArray(new Integer[0]);
quickSortRecursive(nums, 0, list.size() - 1);
return Arrays.asList(nums);
}
/**
* 功能描述: 快速排序逻辑方法
*
* @Author: chenxin
* @Param: [nums, head, bottom]
* @Date: 2020/9/11
*/
private void quickSortRecursive(Integer[] nums, int head, int bottom) {
int i, j, t, tag;
if (head > bottom)
return; // 头大于尾 返回
tag = nums[head]; // 每次将头给一个基数
i = head;
j = bottom;
while (i != j) // 从两头向中间走 当ij相遇则停止
{
// 先从右边开始 如果找到的数小于基数(一般是大于基数 如果小于则代表要换)或者 ij相遇了 则停止
while (nums[j] >= tag && i < j) {
j--;
}
// 然后左边 找到大于基数的数 或者相遇 停止
while (nums[i] <= tag && i < j) {
i++;
}
// 找到两个要换的的数 且此时ij没有相遇 则换
if (i < j) {
t = nums[i];
nums[i] = nums[j];
nums[j] = t;
}
}
// 循环结束 代表ij相遇了 将第i个数当做头 原先的基数变为第i个数
nums[head] = nums[i];
nums[i] = tag;
quickSortRecursive(nums, head, i - 1);
quickSortRecursive(nums, i + 1, bottom);
}
}
7383




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



