三路快排适用于待排序元素存在大量重复的情况,可以接近线性时间复杂度。
public class Test {
public static void main(String[] args){
Random random = new Random();
int[] nums = new int[20];
for (int i = 0;i < nums.length;i++)
{
nums[i] = random.nextInt(5);
}
new Test().quickSort(nums, 0, nums.length - 1);
for (int num : nums)
{
System.out.printf("%d ", num);
}
}
private void quickSort(@NotNull int[] nums, int low, int high)
{
if (low >= high) return;
int lt = low, index = low + 1, gt = high;
//index是工作指针
//最终,lt是第一个等于pivot的地方,index为第一个大于pivot的地方
int pivot = nums[low];
while (index <= gt)
{
if (nums[index] < pivot)
{
swap(nums, index, lt);
index++;
lt++;
}//小于放左边
else
{
if (nums[index] > pivot)
{
swap(nums, index, gt);
gt--;
}//大于放右边,可能交换之后还是比当前数更大
else
{
index++;
}
}
}
quickSort(nums, low, lt - 1);
quickSort(nums, index, high);
}
private void swap(@NotNull int[] nums, int indexA, int indexB)
{
int temp = nums[indexA];
nums[indexA] = nums[indexB];
nums[indexB] = temp;
}
}