Algorithm Manual (7) Fast sorting

Source: Internet
Author: User
Tags sorts

Finally, it's time to come to the classic line. As one of the top ten algorithms in science and engineering in the 20th century, since its invention in 1960s, it has attracted a group of engineers and scientists to improve it, today, we will analyze the fast-forward Algorithm and Its several improvement solutions.

Quick sorting

Overview:
The fast sorting algorithm is also based on the divide and conquer method. Unlike the Merge Sorting Algorithm, it sorts the data in the same place. At the same time, it can sort the time required for the array whose length is N directly proportional to nlogn, the algorithms we have learned cannot combine these two advantages.

The reason for the popularity of quick sorting is that it is easy to implement, suitable for a variety of input data and is much faster than other algorithms in general applications. It may be the most widely used algorithm.

Analysis:

Fast sorting is a Sort Algorithm for grouping. It divides an array into two sub-arrays and sorts the two parts independently. When both sub-arrays are ordered, the entire array is naturally ordered. In fast sorting, the position of the partition depends on the content of the array. The key of this algorithm is splitting. This process must meet three conditions:

1. For a J, a [J] has been scheduled;

2. All elements from a [lo] to a [J-1] are not greater than a [J];

3. All elements in a [J + 1] to a [HI] are not smaller than a [J];

According to the induction method, it is not difficult to prove that he can correctly sort the array: If the left and right sub-arrays are both ordered, then the left sub-array, split element, the result array composed of the right sub-array must also be ordered. It is a randomization algorithm, because it will be disordered before sorting, so it is expected to predict the performance characteristics of the algorithm.

Here, the general splitting policy is to randomly take a [lo] As the splitting element, and then scan from left to right until we find an element greater than or equal to it, scan from right to left until an element smaller than or equal to it is found. We swap the positions of the two elements. In this way, we can ensure that the elements of the pointer I are not greater than the split element, and the elements of the right pointer J are not less than the split element. When I and j meet, exchange a [lo] with a [J] and return J.

Implementation:

public class Quick    {        public static void sort(IComparable[] a)        {

Randomshuffle. Shuffle ();

            sort(a, 0, a.Length - 1);        }        private static void sort(IComparable[] a, int lo, int hi)        {            if (hi <= lo) return;            int j = partition(a, lo, hi);            sort(a, lo, j - 1);            sort(a, j + 1, hi);        }        private static int partition(IComparable[] a, int lo, int hi)        {            int i = lo, j = hi + 1;            IComparable v = a[lo];            while (true)            {                while (less(a[++i], v)) if (i == hi) break;                while (less(v, a[--j])) if (i == lo) break;                if (i >= j) break;                exch(a, i, j);            }            exch(a, lo, j);            return j;        }        private static bool less(IComparable i, IComparable j)        {            return i.CompareTo(j) < 0;        }        private static void exch(IComparable[] a,int i, int j)        {            var temp=a[i];            a[i] = a[j];            a[j] = temp;        }        public static void test(int size)        {            var stopWatch = new Stopwatch(DateTime.Now);            Data[] data = new Data[size];            Random rd = new Random();            for (int i = 0; i < size; i++)            {                data[i] = new Data { value = rd.Next(10000000) };                Console.WriteLine(data[i]);            }            Console.WriteLine("After sort:");            Quick.sort(data);            for (int i = 0; i < size; i++)            {                Console.WriteLine(data[i]);            }            stopWatch.elapsedTime();                   }        public static void Main(string[] args)        {            test(100);        }    }

Note:

1. In-situ splitting

If secondary arrays are used, sharding can be easily implemented, but the overhead of copying the split array back may be unacceptable, which greatly reduces the algorithm sorting speed.

2. Do not cross the border

If the split element is the smallest or largest element in the array, we need to ensure that the number of scan Groups runs out of the boundary, and we need to implement a clear detection to prevent this situation.

3. Maintain randomness

The order of array elements is disrupted, and all its sub-arrays are also sorted randomly, which is important for the running time of the prediction algorithm and can also reduce the probability of the worst case.

4. Terminate the cycle

Experienced programmers understand that it is important to take extra care to terminate the loop, and the sharding loop of fast sorting is no exception. A common error is that the array may contain other elements with the same value as the split element.

5. Duplicate cut points

In this implementation algorithm, it is best to stop the left-side scan when the value is greater than or equal to the cut value, and the right-side scan stops when the cut value is less than or equal to the cut value. Although this may exchange some equivalent elements, in some typical applications, this can avoid changing the algorithm runtime to a square level.

6. Terminate Recursion

Experienced programmers must be careful when ensuring that recursion can always end. A common mistake in fast sorting is that it cannot ensure that the splitting element is placed in the correct position, resulting in the infinite recursion of the program when the splitting element is the maximum or minimum value.

 

Summary:

The quick sorting has been analyzed in detail in mathematics, so we can precisely describe its performance. The inner loop of the fast sorting and splitting method compares the array elements with a fixed value using an incremental index. It is hard to imagine that there is a shorter inner loop in the sorting algorithm.

Another advantage of quick sorting is that it has a relatively small number of comparisons. The best case for quick sorting is that each time an array is accurate to half, in this case, the sub-governance recursion Cn = 2CN/2 + N formula is satisfied, that is, CN ~ Nlogn.

Although quick sorting has many advantages, its basic implementation has a potential disadvantage: It is extremely inefficient in splitting imbalance. Before the fast sorting, we randomly disrupt the array to prevent this situation, which can minimize the possibility of poor splitting.

Algorithm Manual (7) Fast 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.