美文网首页
快速排序

快速排序

作者: 华雨欣 | 来源:发表于2020-11-09 10:04 被阅读0次

用途

快速排序作为最快的排序算法之一,代码比较简洁,在面试中可能会被问到;另一方面,快排由于每次可以确定一个位置,比它大和比它小的数均会分布在两边,所以一般在第K个问题前K个问题后K个问题中会有很优秀的表现。

模板-递归实现

/**
 * 快速排序
 * 
 * @param nums 待排序数组
 * @param l    开始位置下标
 * @param h    结束位置下标
 */
public void QuickSort(int[] nums, int l, int h) {
    if (l >= h) {
        return;
    }
    int index = getIndex(nums, l, h);
    QuickSort(nums, l, index - 1);
    QuickSort(nums, index + 1, h);
}

public int getIndex(int[] nums, int l, int h) {
    int temp = nums[l];
    while (l < h) {
        while (l < h && nums[h] >= temp) {
            h--;
        }
        nums[l] = nums[h];

        while (l < h && nums[l] <= temp) {
            l++;
        }
        nums[h] = nums[l];
    }
    nums[l] = temp;
    return l;
}

注意:参数中的l, h均是数组的下标

模板-非递归版

public void quickSort(int[] nums) {
    int n = nums.length;
    Node all = new Node(0, n - 1);
    Stack<Node> stack = new Stack<Node>();
    stack.push(all);
    while (!stack.isEmpty()) {
        Node temp = stack.pop();
        int start = temp.start;
        int end = temp.end;
        int target = nums[start];
        int l = start, h = end;
        while (l < h) {
            while (l < h && nums[h] >= target) {
                h--;
            }
            nums[l] = nums[h];
            while (l < h && nums[l] <= target) {
                l++;
            }
            nums[h] = nums[l];
        }
        nums[l] = target;
        Node left = new Node(start, l - 1);
        Node right = new Node(l + 1, end);
        if (l + 1 < end)
            stack.push(right);
        if (start < l - 1)
            stack.push(left);
    }
}

class Node {
    int start;
    int end;

    public Node(int start, int end) {
        this.start = start;
        this.end = end;
    }
}

非递归版主要维护一个栈和下标,显得比较臃肿,没有递归方法那么简洁。另外,结点类Node可以采用每次向栈中压两个数、取两个数来代替;非递归的循环中其实也包含了getIndex方法的代码,抽取出来也可以让代码看着简洁。

相关文章

  • 七大排序算法之快速排序

    七大排序算法之快速排序 @(算法笔记)[排序算法, 快速排序, C++实现] [TOC] 快速排序的介绍: 快速排...

  • 面试准备--排序

    堆排序 快速排序(simple) 快速排序(regular) 归并排序 Shell排序 插入排序 选择排序 冒泡排序

  • 排序

    插入排序 选择排序 冒泡排序 归并排序 快速排序* 三路快速排序

  • 算法笔记01-排序#2

    快速排序敢叫快速排序,那它一定得快。 快速排序 概述 快速排序也是分治排序的典型,它快,而且是原地排序。不过,要防...

  • PHP 实现快速排序

    导语 这篇了解下快速排序。 快速排序 快速排序(英语:Quicksort),又称划分交换排序(partition-...

  • 快速排序的Python实现

    目录 快速排序的介绍 快速排序的Python实现 快速排序的介绍 快速排序(quick sort)的采用了分治的策...

  • 数据结构与算法 快速排序

    起因:快速排序,又称分区交换排序,简称快排,之前没有了解过,抽空学习一下。 快速排序 1 快速排序 快速排序的定义...

  • 数组-快速排序

    采用快速方式对数组进行排序 快速排序百科:快速排序(Quicksort)是对冒泡排序算法的一种改进.快速排序是通过...

  • OC数据结构&算法

    更多整理资料尽在?一平米小站 目录 选择排序 冒泡排序 插入排序 快速排序 双路快速排序 三路快速排序 堆排序 选...

  • 要成功就做一百题-94

    题目名称 今天来几个排序,都是经典题目,包括带拆分的快速排序,堆排序,归并排序。 描述 快速排序快速排序核心就是分...

网友评论

      本文标题:快速排序

      本文链接:https://www.haomeiwen.com/subject/zdqlbktx.html