C + + for fast Sorting (recursive)

Source: Internet
Author: User

Fast sorting is an algorithm with a good average performance, and its expected run time is O (NLGN), and the hidden constant factor is very small. But its worst run time is O (n^2). In the end I will analyze it. The Quick Sort key section is divided into two parts:

1. Array Partitioning process :

Use an array with its last element as the principal, and then divide the array around it so that the array elements before this element are smaller than it , and the array elements that follow are larger than it , and the partitioning process is as follows:


The implementation code is as follows:

int Partition (int a[],int low,int high) {//pass parameter array, upper and lower bounds of array
int x = A[high],i = low-1;
for (int j = low;j <= high-1;++j) {
if (A[j] <= x) {
++i;
Swap (a[i],a[j]);//Swap element position
}
}
Swap (A[i+1],a[high]);
return i+1;
}

Here is the element exchange function:

void Swap (int& first, int& second) {
int tem = 0;
TEM = First;
first = second;
second = tem;
}

2. Quick Sort Recursive implementation :

void QuickSort (int a[],int low,int high) {
if (Low < high) {//recursive termination condition
int q = Partition (A,low,high); Find the main element location
QuickSort (a,low,q-1);//fast sorting of arrays prior to the primary location
QuickSort (A,q+1,high);//fast sorting of arrays after the primary location
}
}

3. algorithm worst case Analysis :

The worst case scenario of the algorithm is that the partitioning process consists of 1 and n-1 elements, such as array elements that are already ordered, but the array is partitioned to allow for self-swapping of elements that are smaller than the main element. In the worst case, the algorithm has a time complexity of O (n^2).

C + + for fast Sorting (recursive)

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.