5.快速排序
5.1排序思路
快速排序很多人在第一次见到时,会很懵,因为这个算法很多老师讲的不是太好,这个算法确实不好讲,但是你只要理解了快速排序的思路之后,就会发现这个算法真的很简单。小伙伴们可以结合这张图,与下面的第一次排序,就很一目了然,有什么不懂的地方欢迎大家一起在评论区交流学习。
5.2具体实现
1.第一次
public class QuickSort1 {
public static void main(String[] args) {
int[] array = {3, 5, 7, 8, 9, 1, 2, 6};
quickSort(array, 0, array.length - 1);
System.out.println(Arrays.toString(array));
}
public static void quickSort(int[] array, int start, int end) {
//把数组中的第0个数字作为标准数
int stand = array[start];
//记录需要排序的下标
int low = start;
int high = end;
//循环找比标准数大的数和小的数
while (low < high) {
//如果右边的数比标准数大,则high左移一位
while (low < high && stand <= array[high]) {
high--;
}
//找到一个比标准数小的
array[low] = array[high];
//如果左边的数比标准数大,则low右移一位
while (low < high && stand >= array[low]) {
low++;
}
//找到一个比标准数大的
array[high] = array[low];
}
//将标准数替换掉重合的数
array[low] = stand;
}
}
[2, 1, 3, 8, 9, 7, 5, 6]
2.递归
public class QuickSort1 {
public static void main(String[] args) {
int[] array = {3, 5, 7, 8, 9, 1, 2, 6};
quickSort(array, 0, array.length - 1);
System.out.println(Arrays.toString(array));
}
public static void quickSort(int[] array, int start, int end) {
//递归结束的条件
if (start < end) {
//把数组中的第0个数字作为标准数
int stand = array[start];
//记录需要排序的下标
int low = start;
int high = end;
//循环找比标准数大的数和小的数
while (low < high) {
//如果右边的数比标准数大,则high右移一位
while (low < high && stand <= array[high]) {
high--;
}
//找到一个比标准数小的
array[low] = array[high];
//如果左边的数比标准数大,则low左移一位
while (low < high && stand >= array[low]) {
low++;
}
//找到一个比标准数大的
array[high] = array[low];
}
//将标准数替换掉重合的数
array[low] = stand;
//将比标准数小的再排序
quickSort(array, start, low);
//将比标准数大的再排序
quickSort(array, low + 1, end);
}
}
}
[1, 2, 3, 5, 6, 7, 8, 9]
5.3测试快速排序算法速度
public class QuickSort1 {
public static void main(String[] args) {
int[] arr = new int[80000];
for (int i = 0; i < 80000; i++) {
arr[i] = (int) (Math.random() * 800000);
}
Date date1 = new Date();
SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String format1 = simpleDateFormat1.format(date1);
System.out.println("排序前的时间是:" + format1);
//System.out.println("排序前:"+Arrays.toString(arr));
quickSort(arr, 0, arr.length - 1);
//System.out.println("排序后:"+Arrays.toString(arr));
Date date2 = new Date();
SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String format2 = simpleDateFormat2.format(date2);
System.out.println("排序后的时间是:" + format2);
}
public static void quickSort(int[] array, int start, int end) {
if (start < end) {
//把数组中的第0个数字作为标准数
int stand = array[start];
//记录需要排序的下标
int low = start;
int high = end;
//循环找比标准数大的数和小的数
while (low < high) {
//如果右边的数比标准数大,则high右移一位
while (low < high && stand <= array[high]) {
high--;
}
//找到一个比标准数小的
array[low] = array[high];
//如果左边的数比标准数大,则low左移一位
while (low < high && stand >= array[low]) {
low++;
}
//找到一个比标准数大的
array[high] = array[low];
}
//将标准数替换掉重合的数
array[low] = stand;
//将比标准数小的再排序
quickSort(array, start, low);
//将比标准数大的再排序
quickSort(array, low + 1, end);
}
}
}
排序前的时间是:2021-01-09 15:55:29
排序后的时间是:2021-01-09 15:55:29