4 Sorts of sorting algorithms

Source: Internet
Author: User
Tags sorts

1. Bubble sort

Bubble sort is actually based on "swap". Each time starting from the first record, one, 22 records compared, large back-up, 232 records comparison ... This, in turn, is a bubbling sort. After each bubbling sort, the record with the highest value in the unordered sequence is taken to the end of the sequence, so called bubble sort

function Bubblesort (&$_arr) {$len =count ($_arr);
External loop control number for ($j = $len; $j >0; $j--) {
Control the number of comparisons for ($i =0; $i < $j-1; $i + +) {if ($_arr[$i]>$_arr[$i +1]) {$temp =$_arr[$i];$_arr[$i]=$_arr[$i +1];$_arr[$i + 1]= $temp;}}}

Efficiency Analysis

The number of bubbles in the sort exchange is significantly more than the simple selection sort. It is through the constant exchange of the biggest number out of the way.

The bubble sort average time and worst case (reverse order) time is O (n^2), in the best case without swapping, but the number of comparisons is not reduced, the time complexity is still O (n^2). In addition the bubbling sort is stable

2. Select sort

Given the sequence to be sorted a[1......N], select the small element I, and a[i] Exchange, this is a simple selection of sorting. Fixed value, then Exchange index

function Selectsort (&$_arr) {    $len = count ($_arr);    for ($i =0; $i < $len; $i + +) {        $k = $i;        for ($j = $i +1; $j < $len; $j + +) {            if ($_arr[$k] > $_arr[$j])                $k = $j;            if ($k! = $i) {                $tmp = $_arr[$i];                $_arr[$i] = $_arr[$k];                $_arr[$k] = $tmp;}}}}     

Performance Analysis

Simple selection of the number of operations required to record movement, which is better than the bubble sort, in the best case (ordered sequence order) record the number of moves is 0, the worst case (in order to sort sequence) record the number of moves n-1. The outer loop is n-1, and the first I-trip selection is to be n-i. Time per trip: N-i times + Time to move the record (for a constant of 0 or 1, which can be ignored). A total of n-1 was carried out. The time to move the record is ignored, so the total time is (n-1) * (n-i) =n^2-(i+1) *n+i. The time complexity is O (n^2). The number of comparisons is the same in the worst and best cases, so simple selection of sort average time, worst case, best case time complexity is O (n^2)

Direct selection sorting is an in-place sort, and direct selection of the sort is not stable

3. Insert Sort

Given the sequence to be sorted a[1.....N], it is assumed that A[1...I] has been ordered, then we take out a[i+1] inserted into the sequence a[1...i]. This will increase the number of sequential records by 1. Repeat the above operation so that the record is inserted sequentially until the a[n] is inserted into the ordered sequence , sort done

This improves efficiency by finding the last element of an ordered sequence, moving an element while looking at the edge, rather than finding the insertion position and moving the element first.

function Insertsort (&$_arr) {$len = count ($_arr), for ($i =1; $i < $len; $i + +) {$tmp = $_arr[$i]; $j = $i -1;while ($_arr[ $J] > $tmp && $j >=0) {$_arr[$j +1] = $_arr[$j];$_arr[$j] = $tmp; $j--;}}}

Efficiency analysis

It is easy to see that the number of records to be inserted is n-1, where the number of comparisons of the keywords and the number of records moved depends on whether the ordered sequence is basically ordered. In the best case (ordered sequence), the number of comparisons and the number of moves time is O (1), so the time complexity is O (n). In the worst case (reverse order sequence) and average time are O (n^2). From the above analysis, it can be seen that the direct insertion sort is suitable for less record number, A situation in which a given sequence is basically orderly. Familiar with the sorting process we found that direct insertion sequencing is a stable in-place sorting algorithm

4. Quick Sort

 A quick sort is an improvement of the bubbling sort, the bubbling sort comes up with the maximum value popping up, then you can select a value first, then scan the sequence to be sorted, divide the record less than this value into two separate sequences, and then do the above for each of these two sequences. This is the quick sort, we call the selected value the pivot value, and if the pivot value is the maximum value in the sequence, then a quick sort will become a trip to bubble sort

function QuickSort ($_arr) {$len =count ($_arr), if ($len <= 1) return $_arr; $base = $_arr[0]; $left _arr = $right _arr=array (); for ($i =1; $i < $len; $i + +) {if ($_arr[$i]<= $base) {  $left _arr[]=$_arr[$i];} else{  $right _arr[]=$_arr[$i];}}      $left _arr=quicksort ($left _arr), $right _arr=quicksort ($right _arr), $arr =array_merge ($left _arr, Array ($base), $right _arr); return $arr;}

Efficiency Analysis

Best case, each partition is symmetric, because the pivot value is no longer considered, so the size of the resulting two sub-problems can not be greater than N/2, while a fast sequencing time of O (n), so the run time recursive expression: T (n) <=2t (N/2) +o (n). This recursive solution, please refer to the next blog in the merger sorting efficiency analysis. The solution is T (n) =o (N*LOGN).

Worst case, each partition is very asymmetric, T (n) =t (n-1) +o (n), can be used to solve the recursive tree, the cost of layer I is n-i+1. There are n layers in total. Add up the cost of each layer with N-1 N added. So this recursive solution is T (n) =o (n^2), and this is the bubble sort.

There are two more concepts to understand.

1. internal and external sorting

Sort, the amount of data that participates in sorting is small, and all the data that participates in sorting can be stored in memory in the sorting process.

Sorting, the amount of data to be sorted is so large that memory is not enough to hold all the data at once, and the sorting process needs to be sorted by exchanging data between memory and external memory.

2. stability sequencing and non-stability sequencing

Items that participate in sorting are called sort codes or sort items.

This concept is for situations where there are multiple identical sort items participating in the sort.

If the relative position of these same sort items remains unchanged before sorting by sorting method, then this sort method is called stability sort, otherwise it is non-stable sort.

For example, the order of participation is: A1 = 3, a2 = 6, a3 = 18, A4 = 3, A5 =;

If the stability is sorted, the sort result must be:

A1 = 3, A4 = 3, a2 = 6, a3 =, A5 = 18;

In the case of a non-stable sort, the sorting result might be:

a4 = 3, a1 = 3, a2 = 6, a3 =, A5 = 18;

This changes the relative position of A1 and A4.

4 Sorts of sorting algorithms

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.