快速排序

来源:互联网 发布:linux wc l 编辑:程序博客网 时间:2024/05/16 19:29

1,基本概况

时间复杂度:O(N*log N)

空间复杂度:O(N*log N)

最坏情况:O(N^2)

不稳定


2,思想讲解

总体思想:将输入按照主元(随机选定,后面的实现中选定最后一个元素为主元)划分,使一次划分后主元在中间,左边的元素Ls全都小于主元,右边的元素Rs全都大于主元。再对Ls与Rs依据相同思想进行划分,递归进行下去直至Ls与Rs的长度为1。

3,Java实现

注:选定最后一个元素为主元
<span style="font-family:Microsoft YaHei;">public class main {public static void main(String[] args) {// TODO Auto-generated method stubint[] inputs = new int[] { 1, 6, 2, 5, 8, 6, 9, 8, 7, 1, 2, 3, 5, 56,5, 2 };quickSort(inputs, 0, inputs.length - 1);print(inputs);}public static void quickSort(int[] inputs, int start, int end) {int t = 0;if (start < end) {t = partition(inputs, start, end);if (t > start)quickSort(inputs, start, t - 1);if (t < end)quickSort(inputs, t + 1, end);}}public static int partition(int[] inputs, int start, int end) {int flag = inputs[end];int i = start;int j = start;while (inputs[i] < flag) {i++;j++;}while (j <= end) {while (inputs[j] > flag) {j++;}int t = inputs[j];inputs[j] = inputs[i];inputs[i] = t;i++;j++;}System.out.print("Partition:");print(inputs);return i - 1;}public static void print(int[] inputs) {for (int i : inputs) {System.out.print(i + " ");}System.out.println();}}</span>



0 0
原创粉丝点击