3 of basic sorting algorithms -- quick sorting

Source: Internet
Author: User

The idea of fast sorting is not mentioned. The central axis group uses a temporary unit. Time complexity O (nlogn ). The following is an implementation:

 
# Include <iostream> using namespace STD; Template <typename T> bool _ less (t a, t B) {return a <B ;}template <typename t, typename F> void qsort (t a [], int N, f = _ Less <t>) {If (n <2) return; int first = 0, last = n-1; t temp = A [0]; while (first! = Last) {While (first! = Last &&! F (a [last], temp) last --; A [first] = A [last]; while (first! = Last & F (a [first], temp) First ++; A [last] = A [first];} A [first] = temp; qsort (, first, f); qsort (a + last + 1, n-last-1, f);} template <typename T> void show (t a [], int N) {for (INT I = 0; I <n; ++ I) {cout <A [I] <'';}cout <Endl ;}int main () {float a [] = {3.22, 4.6, 1.27, 9.81, 5.5, 0.12, 2.75, 6.7, 7.01}; qsort (A, 10, _ Less <float>); show (A, 10); Return 0 ;}

Notes:

1. The template class supports default template parameters. Template functions or member template functions do not support the default template parameters (the sort in STL supports the third parameter by reloading the two functions! Instead of using the default template parameters !!)

2. Do not write type parameters for template function calls. The Compiler automatically deduce them.

3. The key to recursion is whether the boundary condition is fully considered.

4. Reference Table: it is incorrect to select the first element as the center. Median of three partitioning is commonly used )!! Is to take the center value of a [first], a [last], a [(first + last)/2.

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.