快速排序
图片来源: https://www.runoob.com/w3cnote/quick-sort-2.html
package com.miracle.study.sort;
import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
/**
* @author Miracle
* @date 2021/4/6 15:36
*/
public class QuickSort {
/**
* 简单快速排序
* @param sortData
* @return
*/
public List<Integer> simpleQuickSort(List<Integer> sortData){
// 判断是否还能够分
if (sortData.size() <= 1){
return sortData;
}
// 获取中间分离值
var x = sortData.get(0);
// 获取左边数据
var left = sortData.stream().filter(data -> data < x).collect(Collectors.toList());
// 获取中间数据
var mid = sortData.stream().filter(data -> data.equals(x)).collect(Collectors.toList());
// 获取右边数据
var right = sortData.stream().filter(data -> data > x).collect(Collectors.toList());
// 继续分左边
simpleQuickSort(left);
// 继续分右边
simpleQuickSort(right);
// 左边合并中间数据
left.addAll(mid);
// 左边合并右边数据
left.addAll(right);
return left;
}
/**
* 复杂快速排序,性能更佳
* @param sortData
* @param left
* @param right
* @return
*/
public int[] quickSort(int[] sortData, int left, int right){
// 判断是否还能够分
if (right - left <= 1){
return sortData;
}
int i = partition(sortData, left, right);
quickSort(sortData, left, i);
quickSort(sortData, i + 1, right);
return sortData;
}
private int partition(int[] sortData, int left, int right) {
var x = sortData[left];
int i = left + 1;
int j = right;
while (i != j){
if (sortData[i] < x){
i++;
}else {
j--;
var cacheData = sortData[i];
sortData[i] = sortData[j];
sortData[j] = cacheData;
}
}
// 将x与最后计算小于x的值互换,达成左边全部是小于x的值,右边全是大于的值
var cacheData = sortData[i - 1];
sortData[i - 1] = sortData[left];
sortData[left] = cacheData;
return i - 1;
}
@Test
public void test(){
// List<Integer> integers = simpleQuickSort(Arrays.asList(1, 5, 7, 9, 3, 6, 8, 4, 2, 10, 0, 19));
// integers.stream().forEach(integer -> System.out.println(integer));
var sortData = new int[]{1, 5, 7, 9, 3, 6, 8, 4, 2, 10, 0, 19};
var intArray = quickSort(sortData, 0, sortData.length);
Arrays.stream(intArray).forEach(integer -> System.out.println(integer));
}
}