Use Go for quick sorting

Source: Internet
Author: User

Fast sorting (Quick sort) claims to be one of the greatest ten algorithms of the 20th century (the best of the 20th century:editors Name Top ten algorithms), but fast sorting is also one of the least easily implemented sorting algorithms (). Although the principle is very simple, it is easy to make mistakes. Also because the fast platoon causes reign even the website attack event.

Quick Sort by C. A. R. Hoare was introduced in 1962. Its basic idea is: by a trip to sort the data to be sorted into two separate parts, one part of all the data is smaller than the other part of all the data, and then the two parts of the data are quickly sorted by this method, the entire sorting process can be recursive, so as to achieve the entire data into an ordered sequence.

Divide and conquer: Divide the problem into several sub-problems that are smaller in size but similar in structure to the original problem. Solve these sub-problems recursively, then combine the solutions of these sub-problems into the solution of the original problem.

Using the divide-and-conquer method can be divided into three steps of rapid sequencing:

    • In the dataset, select an element as the Datum (pivot).
    • All elements that are smaller than the datum are moved to the left of the datum, and all elements that are larger than the datum are moved to the right of the datum. This operation is called a partition (partition) operation, where the base element is positioned after the final sort after the partition operation has ended.
    • For the two subsets to the left and right of the Datum, repeat the first and second steps until only one element is left in all the subsets.

Quick sort Average time complexity is O(n log n) , worst case is O(n2) , unstable sort.

Fast sorting is generally implemented as in-place ordering (in-place), because non-in-place sorting is designed to be a large number of container creation and object replication.

This paper realizes two kinds of quick sort, one is single-threaded fast sort, and the other is a certain number of goroutine parallel fast sort.

The comparison between the standard library sorting algorithm and the Timsort algorithm is also added.

Here is the algorithm implementation:

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465 66676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
 PackageMainImport("FMT""Math/rand""Sort""Time""Github.com/psilva261/timsort")funcPartition (A []int, Lo, HIint)int{pivot: = a[hi]i: = Lo-1 forJ: = Lo; J < Hi; J + + {ifA[J] < pivot {I++A[J], a[i] = A[i], a[j]}}a[i+1], A[hi] = A[hi], a[i+1]returni +1}funcQuickSort (A []int, Lo, HIint) {ifLo >= Hi {return}p: = Partition (A, lo, HI) quickSort (A, lo, p-1) QuickSort (A, p+1, HI)}funcQuicksort_go (A []int, Lo, HIint, doneChan struct{}, Depthint) {ifLo >= Hi {done <-struct{}{}return}depth--p: = Partition (A, lo, HI)ifDepth >0{Childdone: = Make(Chan struct{},2)GoQuicksort_go (A, lo, p-1, Childdone, depth)GoQuicksort_go (A, p+1, Hi, childdone, depth) <-childdone<-childdone}Else{QuickSort (A, lo, p-1) QuickSort (A, p+1, HI)}done <-struct{}{}}funcMain () {rand. Seed (time. Now (). Unixnano ()) testData1, TestData2, testData3, testData4: = Make([]int,0,100000000), Make([]int,0,100000000), Make([]int,0,100000000), Make([]int,0,100000000) Times: =100000000 forI: =0; I < times; i++ {val: = rand. Intn(20000000) TestData1 =Append(TestData1, val) testData2 =Append(TestData2, val) testData3 =Append(TestData3, val) testData4 =Append(TestData4, Val)} Start: = time. Now () QuickSort (TestData1,0,Len(testData1)-1) FMT. Println ("single goroutine:", time. Now (). Sub (start))if!sort. Intsaresorted (testData1) {fmt. Println ("wrong Quick_sort implementation")}done: = Make(Chan struct{}) Start = time. Now ()GoQuicksort_go (TESTDATA2,0,Len(TestData2)-1, Done,5) <-donefmt. Println ("multiple goroutine:", time. Now (). Sub (start))if!sort. Intsaresorted (TESTDATA2) {fmt. Println ("wrong Quicksort_go implementation")}start = time. Now () sort. Ints (TESTDATA3) fmt. Println ("std lib:", time. Now (). Sub (start))if!sort. Intsaresorted (testData3) {fmt. Println ("wrong Std lib implementation")}start = time. Now () Timsort. Ints (TESTDATA4,func(A, Bint)BOOL{returnA <= B}) fmt. Println ("Timsort:", time. Now (). Sub (start))if!sort. Intsaresorted (TESTDATA4) {fmt. Println ("wrong Timsort implementation")}}
Related Article

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.