赞
踩
写在前面
快速排序主要采用分治的基本思想,每次将一个位置上的数据归位,此时该数左边的所有数据都比该数小,右边所有的数据都比该数大,然后递归将已归位的数据左右两边再次进行快排,从而实现所有数据的归位。
package com.zhuang.algorithm; import java.util.Arrays; /** * @Classname QuickSort * @Description 快速排序 * @Date 2021/6/13 16:21 * @Created by dell */ public class QuickSort { public static void main(String[] args) { int[] arr = {5, 2, 4, 8, 1, 9, 3, 15}; quickSort(arr, 0, arr.length - 1); System.out.println(Arrays.toString(arr)); } public static void quickSort(int[] arr, int low, int high) { if (low < high) { //将数组分为两部分 int index = getIndex(arr, low, high); //递归排序左子数组 quickSort(arr, low, index - 1); //递归排序右子数组 quickSort(arr, index + 1, high); } } public static int getIndex(int[] arr, int low, int high) { //基准temp int temp = arr[low]; while (low < high) { while (low < high && arr[high] >= temp) { high--; } //交换比基准大的记录到左端 arr[low] = arr[high]; while (low < high && arr[low] <= temp) { low++; } //交换比基准小的记录到右端 arr[high] = arr[low]; } //扫描完成,基准到位 arr[low] = temp; // 返回基准的位置 return low; } }
快速排序并不是稳定的。这是因为我们无法保证相等的数据按顺序被扫描到和按顺序存放。
快速排序在大多数情况下都是适用的,尤其在数据量大的时候性能优越性更加明显。但是在必要的时候,需要考虑下优化以提高其在最坏情况下的性能
写在最后
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。