Quick Sort

(referrence: GeeksforGeeks)

Like Merge Sort, Quick Sort is also a divide & conquer problem.

It picks an element as pivot and partitions the given array around the picked pivot.

Different versions of Picking pivot

1. Always pick first element as pivot.
2. Always pick last element as pivot (implemented below)
3. Pick a random element as pivot.
4. Pick median as pivot.

Partition Algorithm

Target: Given an array and an element x of array as pivot, put x at its correct position in sorted array and put all smaller elements (smaller than x) before x, and put all greater elements (greater than x) after x.

Follow the method given in CLRS book, we pick last element as pivot.

We start from the leftmost element and keep track of index of smaller (or equal to) elements as i. While traversing, if we find a smaller element, we swap current element with arr[i]. Otherwise we ignore current element.

Example

 1 public class Solution {
 2     private void swap(int[] nums, int index1, int index2) {
 3         int tmp = nums[index1];
 4         nums[index1] = nums[index2];
 5         nums[index2] = tmp;
 6     }
 7
 8     // Pick last element as pivot
 9     // Place all smaller elements before pivot
10     // Place all bigger elements after pivot
11     private int partition(int[] nums, int start, int end) {
12         int pivot = nums[end];
13         int currentSmaller = start - 1;
14         for (int i = start; i < end; i++) {
15             // If current element <= pivot, put it to right position
16             if (nums[i] <= pivot) {
17                 currentSmaller++;
18                 swap(nums, i, currentSmaller);
19             }
20         }
21         // Put pivot to right position
22         currentSmaller++;
23         swap(nums, end, currentSmaller);
24         return currentSmaller;
25     }
26
27     public void quickSort(int[] nums, int start, int end) {
28         // Stop criterion: start = end
29         if (start < end) {
30             int p = partition(nums, start, end);
31             quickSort(nums, start, p - 1);
32             quickSort(nums, p + 1, end);
33         }
34     }
35 }

Time Complexity Analysis

For partition step, time complexity is O(n).

Time taken by Quick Sort in general can be written as following:

T(n) = T(k) + T(n - k - 1) + O(n)

1. Worst Case:

The worst case occurs when the partition process always picks greatest or smallest element as pivot. If we consider above partition strategy where last element is always picked as pivot, the worst case would occur when the array is already sorted in increasing or decreasing order.

T(n) = T(n - 1) + O(n) -> T(n) = O(n2)

2. Best Case:

The best case occurs when the partition process always picks the middle element as pivot.

T(n) = 2T(n/2) + O(n) -> T(n) = O(n log n)

3. Average Case:

We can get an idea of average case by considering the case when partition puts O(n/9) elements in one set and O(9n/10) elements in other set.

T(n) = T(n/9) + T(9n/10) + O(n) -> T(n) = O(n log n)

Compared with Merge Sort

QuickSort is faster in practice, because its inner loop can be efficiently implemented on most architectures, and in most real-world data. QuickSort can be implemented in different ways by changing the choice of pivot, so that the worst case rarely occurs for a given type of data. However, merge sort is generally considered better when data is huge and stored in external storage.

时间: 2024-10-20 05:39:03

Quick Sort的相关文章

快速排序(Quick Sort)的C语言实现

快速排序(Quick Sort)的基本思想是通过一趟排序将待排记录分割成独立的两部分,其中一部分记录的关键字均比另一部分记录的关键字小,则可分别对着两部分记录继续进行排序,以达到整个序列有序,具体步骤为 设立枢轴,将比枢轴小的记录移到低端,比枢轴大的记录移到高端,直到low=high停止 分别对枢轴低高端部分再次快速排序(即重复第1步) 重复第1.2步,直到low=high停止 C语言实现(编译器Dev-c++5.4.0,源代码后缀.cpp) 原创文章,转载请注明来自钢铁侠Mac博客http:/

C++: quick sort(快排序)

到目前为止, 我们已经学习到了插入排序, 冒泡排序, 选择排序(selection). 这些排序算法都是comparision based sorting algorithms(即涉及到元素大小的比较来决定元素的先后顺序). 而且算法的时间复杂度上均为O(n^2).但是comparision based 的排序算法远非这几个算法. 而且可以通过利用其它的一些手段(例如divide and conquer technique, 分治法)实现对基于比较的排序算法的时间复杂度降低到O(nlogn).

1101. Quick Sort (25)

There is a classical process named partition in the famous quick sort algorithm. In this process we typically choose one element as the pivot. Then the elements less than the pivot are moved to its left and those larger than the pivot to its right. G

pat1101. Quick Sort (25)

1101. Quick Sort (25) 时间限制 200 ms 内存限制 65536 kB 代码长度限制 16000 B 判题程序 Standard 作者 CAO, Peng There is a classical process named partition in the famous quick sort algorithm. In this process we typically choose one element as the pivot. Then the elements

Iterative (non-recursive) Quick Sort

An iterative way of writing quick sort: #include <iostream> #include <stack> #include <utility> using namespace std; void quickSort(int A[], int n) { stack<pair<int, int>> stk; stk.push(make_pair(0, n-1)); while (!stk.empty()

Quick Sort in Java and Erlang

Quick Sort In Java. public static void quickSort(int[] a, int p, int r) {         if (p < r) {             int q = partition(a, p, r);             quickSort(a, p, q);             quickSort(a, q + 1, r);         }     }     private static int partitio

笔试算法题(54):快速排序实现之单向扫描、双向扫描(single-direction scanning, bidirectional scanning of Quick Sort)

议题:快速排序实现之一(单向遍历) 分析: 算法原理:主要由两部分组成,一部分是递归部分QuickSort,它将调用partition进行划分,并取得划分元素P,然后分别对P之前的部分和P 之后的部分递归调用QuickSort:另一部分是partition,选取划分元素P(随机选取数组中的一个元素,交换到数组末尾位置),定义两个标记 值left和right,随着划分的进行,这两个标记值将数组分成三部分,left之左的部分是小于划分元素P的值,left和right之间的部分是大 于等于划分元素P的

排序算法之快速排序(Quick Sort) -- 适用于Leetcode 75 Sort Colors

Quick Sort使用了Divide and Concur的思想: 找一个基准数, 把小于基准数的数都放到基准数之前, 把大于基准数的数都放到基准数之后 Worst case: O(n^2) Average case: O(nlogN) 步骤: 初始的数组 Array a[]: 0 1 2 3 4 5 6 7 8 9 51 73 52 18 91 7 87 73 48 3 基准数: X = a[0] = 51 i 的值: i = 0 j 的值: j = 9 (a.length) Step 1:

Implementation: Quick Sort 2014-08-19

1 #include <stdio.h> 2 3 void print(int *a, int start , int end); 4 5 void quick_sort(int *a, int start, int end) { 6 if (start + 1 >= end) return; 7 int pv = a[start]; 8 int p = start, q = end; 9 for (;;) { 10 while (++p < end && a[p]