Quick sorting and quick sorting algorithms

Source: Internet
Author: User

Quick sorting and quick sorting algorithms

Quick Sorting Algorithm

1. algorithm ideas

Sort the input array a [I, j:

1) decomposition: the input array is divided into three parts: a [I, k-1], a [k], and a [k + 1, j]. so that the elements in a [I, k-1] are not greater than (or less than) a [k], and a [k + 1, j] are greater than (or not less) a [k];

2) recursive solution: Call the quick sorting algorithm recursively to sort each part;

2. Algorithm Implementation

template<class T>int Partition(T a[], int left, int right){    T x = a[left];    while(left < right){        while( a[right] >= x && left < right)  right--;        if(left < right)  a[left++] = a[right];        while( a[left] <= x && left < right)  left++;        if(left < right) a[right--] = a[left];     }    a[right] = x;    return right;}template<class T>void QuickSort(T a[], int left, int right){    if(left < right){        int temp = Partition(a, left, right);        QuickSort(a, left, temp - 1);        QuickSort(a, temp + 1, right);    }}

3. Algorithm Analysis

The best time complexity of the quick sorting algorithm is round (nlog (n). At this time, the benchmark obtained each time is exactly the middle value, and the average time complexity is round (nlog (n )). However, when the benchmark is at the extreme of data, such as the maximum or minimum value of this sort, it will increase the time complexity. In the worst case, the input data is just ordered, and the time complexity is second (n2 ).

4. Algorithm Improvement

You can change the benchmark to reduce the worst time complexity in a quick sorting algorithm. You can modify the baseline of the original quick rank to generate a random number r (left <= r <= right) before selecting the benchmark ), then, the data corresponding to the random number position is exchanged with the first data in the sorting order, which can effectively reduce the extreme situations in sorting.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.