Data Structure and Algorithms
  • Introduction
  • 面经
    • 亚马逊面经
  • Sorting
    • Quick Sort
    • Merge Sort
    • Heap Sort
  • Palindrome
    • Check String Palindrom
    • Palindrome Partitioning
    • Palindrome Partitioning II
    • Longest Palindromic Substring
    • Valid Palindrome
  • Linked List
    • Remove Duplicates from Sorted List
    • Remove Duplicates from Sorted List II
    • Remove Nth Node From End of List
    • Remove Linked List Elements
    • Remove Duplicates from Unsorted List
    • Remove duplicate Circular Linked list
    • Reverse Linked List
    • Reverse Linked List II
    • Reverse Nodes in k-Group
    • Partition List
    • Insertion Sort List
    • Reorder List
    • Linked List Cycle
    • Rotate List
    • Merge k Sorted Lists
    • Copy List with Random Pointer
    • Nth to Last Node in List
    • Add Two Numbers
    • Add Two Numbers II
    • Palindrome Linked List
  • Binary Search
    • Sqrt(x)
    • Search a 2D Matrix
    • Search a 2D Matrix II
    • Search Insert Position
    • First Position of Target
    • Last Position of Target
    • Count of Smaller Number
    • Search for a Range
    • Search in a Big Sorted Array
    • First Bad Version
    • Find Minimum in Rotated Sorted Array
    • Find Minimum in Rotated Sorted Array II
    • Search in Rotated Sorted Array
    • Search in Rotated Sorted Array II
    • Find Peak Element*
    • Recover Rotated Sorted Array
    • Rotate String
    • Wood Cut
    • Total Occurrence of Target
    • Closest Number in Sorted Array
    • K Closest Number in Sorted Array
    • Maximum Number in Mountain Sequence
    • Search Insert Position *
    • Pow(x, n)
    • Divide Two Integers
  • Graph
    • Clone Graph
    • Topological Sorting
    • Permutations
    • Permutations II
    • Subsets
    • Subsets II
    • Word Ladder
    • Word Ladder II
    • N-Queens
    • N-Queens II
    • Connected Component in Undirected Graph
    • Six Degrees
    • String Permutation II
    • Letter Case Permutation
  • Data Structure
    • Min Stack
    • Implement a Queue by Two Stacks
    • Largest Rectangle in Histogram
    • Max Tree
    • Rehashing
    • LRU Cache
    • Subarray Sum
    • Anagrams
    • Longest Consecutive Sequence
    • Data Stream Median
    • Heapify
    • Ugly Number
    • Ugly Number II
  • Misc
    • PlaceHolder
    • Fibonacci
  • Array and Numbers
    • Merge Sorted Array
    • Merge Two Sorted Arrays
    • Median of two Sorted Arrays
    • Best Time to Buy and Sell Stock
    • Best Time to Buy and Sell Stock II
    • Best Time to Buy and Sell Stock III
    • Maximum Subarray
    • Maximum Subarray II
    • Maximum Subarray III
    • Minimum Subarray
    • Maximum Subarray Difference
    • Subarray Sum
    • Subarray Sum Closest
    • Two Sum
    • 3Sum
    • 3Sum Closest
    • 4Sum
    • k Sum
    • k Sum II
    • Partition Array
    • Sort Letters by Case
    • Sort Colors
    • Sort Colors II
    • Interleaving Positive and Negative Numbers
    • Spiral Matrix
    • Spiral Matrix II
    • Rotate Image
  • Dynamic Programming I
    • Triangle
    • Minimum Path Sum
    • Unique Paths
    • Unique Paths II
    • Climbing Stairs
    • Jump Game
    • Jump Game II
    • 01 Matrix
    • Longest Line of Consecutive One in Matrix
    • Shortest Path in Binary Matrix
  • Dynamic Programming II
    • Word Break
    • Longest Common Subsequence
    • Longest Common Substring
    • Edit Distance
    • Distinct Subsequences
    • Interleaving String
    • k Sum
  • Binary Tree And Divide Conquer
    • Binary Tree Preorder Traversal*
    • Binary Tree Inorder Traversal*
    • Binary Tree Postorder Traversal*
    • Maximum Depth of Binary Tree
    • Minimum Depth of Binary Tree
    • Balanced Binary Tree
    • Lowest Common Ancestor
    • Binary Tree Maximum Path Sum
    • Binary Tree Maximum Path Sum II
    • Binary Tree Level Order Traversal*
    • Binary Tree Level Order Traversal II
    • Binary Tree Zigzag Level Order Traversal
    • Validate Binary Search Tree
    • Inorder Successor in Binary Search Tree
    • Binary Search Tree Iterator
    • Search Range in Binary Search Tree
    • Insert Node in a Binary Search Tree
    • Remove Node in Binary Search Tree
    • Find the kth largest element in the BST
    • Kth Smallest Element in a BST
    • Serialize and Deserialize Binary Tree*
    • Construct Binary Tree from Preorder and Inorder Traversal
    • Convert Sorted Array to Binary Search Tree
    • Unique Binary Search Trees *
    • Unique Binary Search Trees II *
    • Recover Binary Search Tree
    • Same Tree
    • Symmetric Tree
    • Path Sum*
    • Path Sum II*
    • Flatten Binary Tree to Linked List
    • Populating Next Right Pointers in Each Node
    • Sum Root to Leaf Numbers
    • Binary Tree Right Side View
    • Count Complete Tree Nodes
    • Invert Binary Tree
    • Binary Tree Paths*
    • Subtree of Another Tree
  • A家面试总结
  • Expedia面经收集
  • Python 常用语句
  • lotusflare
  • Microsoft
  • 模板
  • Bing 组面试总结
  • 面试笔记
  • Sliding window
Powered by GitBook
On this page

Was this helpful?

  1. Sorting

Quick Sort

PreviousSortingNextMerge Sort

Last updated 4 years ago

Was this helpful?

快速排序是C.R.A.Hoare于1962年提出的一种划分交换排序。它采用了一种分治的策略,通常称其为分治法(Divide-and-ConquerMethod)。

核心思想就是,找到pivot 然后用这个pivot作为base , 通过双指针的方法,左右移动到pivot,确保,左边的数值全部小于pivot ,右面的数值全部大于pivot,然后再通过divide conquer 进行左右两部分的后续操作,直到不能拆分pivot为止。

代码小技巧:左指针移动比较完成后,一定要落回P点,如果数据都是小于p的。所以合理处理 =

难点: 你的第一次while循环之后,并不能保证此时所有小于分割处的数字在它的左边,大于的在它数在它的右边。

如果只有两个数值的时候,就回出现,left = p 在同一点。

while (left <= right && A[left] < pivot) 循环滑动技巧


https://zhuanlan.zhihu.com/p/34479151

时间复杂度:

在最优情况下,Partition每次都划分得很均匀,如果排序n个关键字,其递归树的深度就为.log2n.+1(.x.表示不大于x的最大整数),即仅需递归log2n次,需要时间为T(n)的话,第一次Partiation应该是需要对整个数组扫描一遍,做n次比较。然后,获得的枢轴将数组一分为二,那么各自还需要T(n/2)的时间(注意是最好情况,所以平分两半)。于是不断地划分下去,我们就有了下面的不等式推断。

  1. T(n)≤2T(n/2) +n,T(1)=0

  2. T(n)≤2(2T(n/4)+n/2) +

    n

    =

    4T

    (n/4)+2n

  3. T(n)≤4(2T(n/8)+n/4) +

    2n

    =

    8T

    (n/8)+3n

  4. ……

  5. T(n)≤nT(1)+(log2n)×

    n

    =

    O

    (nlogn)

也就是说,在最优的情况下,快速排序算法的时间复杂度为O(nlogn)。

平均的情况,设枢轴的关键字应该在第k的位置(1≤k≤n),那么:

public class Solution {
    /**
     * @param A an integer array
     * @return void
     */
    public void sortIntegers2(int[] A) {
        quickSort(A, 0, A.length - 1);
    }

    private void quickSort(int[] A, int start, int end)
        {
            if (start >= end)
            {
                return;
            }

            int left = start, right = end;
            // key point 1: pivot is the value, not the index
            int pivot = A[(start + end) / 2];

            while (left <= right)
            {
                while (A[left] < pivot)
                {
                    left++;
                }
                while (A[right] > pivot)
                {
                    right--;
                }

                if (left <= right)
                {
                    int temp = A[left];
                    A[left] = A[right];
                    A[right] = temp;

                    left++;
                    right--;
                }
            }

            quickSort(A, start, right);
            quickSort(A, left, end);
        }
}

在最坏的情况下,待排序的序列为正序或者逆序,每次划分只得到一个比上一次划分少一个记录的子序列,注意另一个为空。如果递归树画出来,它就是一棵斜树。此时需要执行n‐1次递归调用,且第i次划分需要经过n‐i次关键字的比较才能找到第i个记录,也就是枢轴的位置,因此比较次数为 ,最终其时间复杂度为O(n2)。

https://www.zybuluo.com/Zh1Cheung/note/1076005