package sort;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
/**
* @author taoke
* @desc 快速排序
* @email 1504806660@qq.com
* @date 2022/1/6
*/
public class QuickSort {
public static void main(String[] args) {
int[] arr = new int[30];
for (int i = 0; i < 30; i++) {
arr[i] = (int) (Math.random() * 30);
}
System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
System.out.println(Arrays.toString(sort(0, arr.length - 1, arr)));
System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
}
/**
* 快速排序
*
* @param left 左下标
* @param right 右下标
* @param arr 待排序数组
* @return 排序后结果
*/
private static int[] sort(int left, int right, int[] arr) {
//左下标和右下标相等退出递归
if (left >= right) {
return arr;
}
//定义一个中轴
int pivot = arr[(left + right) / 2];
int temp;
//当前数组低下标
int low = left;
//当前数组高下标
int high = right;
while (low < high) {
//从中轴线坐标左侧找到一个大于中轴数的数
while (arr[low] <= pivot && low < high) {
low++;
}
//从中轴线坐标右侧找到一个小于中轴数的数
while (arr[high] >= pivot && low < high) {
high--;
}
//找到后交换这两个值
if (low < high) {
temp = arr[high];
arr[high] = arr[low];
arr[low] = temp;
}
}
//左侧递归
sort(left, low - 1, arr);
//右侧递归
sort(low + 1, right, arr);
return arr;
}
}
数据结构与算法-排序-快速排序
本文详细介绍了快速排序算法的Java实现,包括主要的排序逻辑和递归过程。通过随机生成的30个整数数组进行演示,展示了排序前后的日期时间,以体现算法执行的时间消耗。该算法以中轴元素为基准,通过两指针策略将数组分为小于和大于中轴的两部分,然后对两部分进行递归排序,最终得到有序数组。
摘要由CSDN通过智能技术生成