Common sorting algorithms-fast sorting

Source: Internet
Author: User

Principles of fast sorting:

First, find a baseline value, which is equal to a certain element value. traverse the array and divide the array into two parts: smaller than the baseline value and greater than the baseline value. Then, sort the two parts quickly and recursively.

 

When the array is separated, a pointer is maintained pointing to the last element that has been found in a small part; a pointer is used for traversing.

 

Unstable sorting algorithm. When the array is ordered, the time complexity is the worst, Which is O (n2). The average and Optimal Values are O (N lgn ).

 

The Code is as follows:

1 # include <iostream> 2 using namespace STD; 3 4 template <typename T> 5 void quicksort (T num [], int first, int last) 6 {7 if (first> = last) 8 return; 9 10 t pviot = num [first]; 11 12 INT small = first; // pointer, point to the last value of a small part that has been processed 13 14 for (INT I = first + 1; I <= last; ++ I) 15 {16 if (Num [I] <= pviot) 17 {18 ++ small; // exchange the first value after a small part with the value smaller than the value found by the packettle 19 if (small <I) 20 {21 swap (Num [small], num [I]); 22} 23} 24} 25 26 swap (Num [first], num [small]); 27 28 quicksort (Num, first, small-1); 29 quicksort (Num, small + 1, last); 30} 31 32 int main () 33 {34 const int n = 5; 35 36 int Ia [N] = {1, 3, 6, 2, 4}; 37 double da [N] = {1.2, 3.4, 6.7, 2.3}; 38 39 quicksort (IA, 0, n-1 ); 40 quicksort (DA, 0, n-1); 41 42 for (INT I = 0; I <n; ++ I) 43 cout <Ia [I] <''; 44 cout <Endl; 45 46 for (INT I = 0; I <n; ++ I) 47 cout <da [I] <''; 48 cout <Endl; 49 50 return 0; 51}

 

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.