Data Structure and algorithm C # edition notes-sorting (SORT)-above

Source: Internet
Author: User

This article only applies to internal sorting (that is, all data is stored in the memory and elements are sorted by CPU operations), and only ordered table sorting (that is, the linked list is not discussed, tree Structure and other structure sorting)

Note: The sorting result can be small to large, or small. This is just the opposite. For convenience, the methods in this article are sorted from small to large.

1. Insert the sorting directly (insertorder)

Idea: traverse backward from the second element and check the size of the adjacent elements (TMP). If the preceding element is larger, then, all the preceding elements are checked from the near and far (that is, inverted traversal), and the elements larger than their own elements are moved back in sequence, so that a vacant space is obtained, insert the TMP element in this position.

/// <Summary> /// insert sort method /// </Summary> /// <Param name = "lst"> </param> static void insertsort (INT [] lst) {int _ circlecount = 0; // the outer loop traverses for (INT I = 1; I <lst. length; I ++) {_ circlecount ++; // console. writeline ("External Loop I =" + I); // If an element is smaller than the previous one, if (LST [I] <lst [I-1]) {int TMP = lst [I]; Int J = 0; // The elements in front of the element are traversed from the back to the front and moved back in sequence, directly locate the empty file to be inserted (so that the TMP element finds its location) for (j = I-1; j> = 0 & TMP <lst [J]; J --) {// If an element is found to be smaller than TMP, the element is moved one by one (to empty itself and form a blank file, so that if there are smaller elements in front, you can move them backward.) lst [J + 1] = lst [J]; _ circlecount ++; // console. writeline ("inner loop I =" + I + ", inner loop J =" + J);} // console. writeline ("J = {0}", J); // when running here, J is already the first subscript of the empty file lst [J + 1] = TMP ;}} console. writeline ("insertorder {0} times in total", _ circlecount );}

Comments: The best case, if all the elements (n) have been sorted out, the External Loop To run the N-1 times, the internal cycle once can not enter, that is, 0 times, time complexity is O (n); worst case, all elements reverse order, External Loop N-1 times, inner loop is I (I from 1 to N-1 ), the time complexity is O (n * n). Therefore, the more elements have sequences, the higher the efficiency of this method. The time complexity is from O (n) to O (N * n). In addition, this method is a stable sorting method. (Note: If an array contains elements with the same values, the order of the elements with the same values remains unchanged after sorting by a method, the sorting method is stable, otherwise, it is an unstable sorting method)

2. bubblesort)

Idea: traverse forward from the last element and check the size of the element and the adjacent element. If the element is larger, the switching position is repeated, until you move yourself to the appropriate position (that is, it is equivalent to the following elements. Through this comparison, we will keep moving the front from small to general, just as the bubbles will go up from below)

/// <Summary> /// bubble sort method /// </Summary> /// <Param name = "lst"> </param> static void bubblesort (INT [] LST) {int _ circlecount = 0; // used for auxiliary purposes. You can remove int TMP; For (INT I = 0; I <lst. length; I ++) {for (Int J = lst. length-2; j> = I; j --) {If (LST [J + 1] <lst [J]) {TMP = lst [J + 1]; LST [J + 1] = lst [J]; lst [J] = TMP;} _ circlecount ++;} console. writeline ("bubbleorder {0} times in total", _ circlecount );}

Comment: similar to the insert sorting method, it is best that all elements are sorted in order so that only external loops are run. Internal loops exit directly because if judgment is not true. The worst case is reverse order of all elements, the external and inner loops must be processed each time. Therefore, the time complexity is exactly the same as the insertion sorting method, which is also a stable sorting method.

3. simpleselectorder)

idea: first scan the entire array, find the smallest element, and then exchange it with the first element (in this way, the elements at the first position are arranged ), then start scanning from the second element, find the second small element, and exchange it with the second element (in this way, the elements in the second position are also arranged )... so repeatedly

/// <Summary> /// simple selection and sorting method /// </Summary> /// <Param name = "lst"> </param> static void simpleselectsort (INT [] lst) {int _ circlecount = 0; // The secondary int TMP = 0; int T = 0; For (INT I = 0; I <lst. length; I ++) {T = I; // The inner loop to find the smallest element subscript for (Int J = I + 1; j <lst. length; j ++) {If (LST [T]> lst [J]) {T = J ;}_ circlecount ++ ;} // swap the minimum element [subscript = T] with element I tmp = lst [I]; lst [I] = lst [T]; lst [T] = TMP ;} console. writeline ("simpleselectsort {0} times in total", _ circlecount );}

Comment: It is similar to the bubble method, but it should be noted that the element exchange operation is outside the internal loop, that is, no matter how the exchange operation is saved, therefore, the time complexity is O (n * n), which is also a stable sorting.

4. Quick order)

Train of Thought: Use the elements in the middle of the array as the demarcation line (this element is called the pivot point), scan other elements, put the elements smaller than the pivot point on the left, put the elements larger than the pivot point on the right, in this way, the array is divided into two segments (that is, a rough sorting), and then the same processing is performed for each segment (that is, the second segment is changed to four segments, 4-segment changed to 8-segment ...), until each last segment has only one element (yes, this method is a recursive call)

/// <Summary> /// fast sorting /// </Summary> /// <Param name = "arr"> list of elements to be sorted </param> /// <param name = "Left"> index of the first element in the array </param> // <Param name = "right"> index of the last element in the array </param> static void quicksort (INT [] arr, int left, int right) {// If (left <right) {// The intermediate element is not sorted as the benchmark, less than his shift to the left, greater than his shift to the right int middle = arr [(left + right)/2]; // because the ++ and -- operations are performed in while, so here I and J are replaced by an extended one int I = left-1; Int J = right + 1; while (true) {While (ARR [++ I] <middle); // If the element value in the first half is smaller than the pivot, skip while directly (ARR [-- J]> middle); // If the element value in the lower half is greater than the pivot, skip directly // because the first half is backward traversal, And the last half is forward traversal, if the two are met, // It indicates that all elements have been scanned, exit if (I> = J) {break;} // after processing, if an element with the wrong position is found, replace the two with int TMP = arr [I]; arr [J] = arr [I]; arr [I] = TMP;} // After the WHILE LOOP above, the element has been divided into the left and right segments (the left segment is less than the pivot, And the right segment is greater than the pivot) // recursive call, processing the left segment quicksort (ARR, left, I-1 ); // recursive call, processing the right segment quicksort (ARR, J + 1, right );}}

Comments: each time, it is divided into two segments from the middle, and then divided into two segments, so repeated... this is very similar to a binary tree (each segment is equivalent to dividing a node in the tree into two forks). It is best to arrange all the elements in order, the number of left and right branches of the final tree is roughly the same (that is, the length of left and right branches is roughly the same), so the number of splits is the height of the tree.Log2NIn the worst case, when all elements are in reverse order, the resulting tree is equivalent to a single right binary tree (that is, a super long right branch without a strange tree with a left branch ), that is, the time complexity range is nlog.2N to N * n. In addition, quick sorting isUnstable(FromCodeIt can be seen that even two nodes with the same value may be exchanged in the segmentation process)

I wanted to write the heap sorting and Merge Sorting together in this article.ArticleIn, today I looked at the heap sorting, but it's a little complicated. I can have another detailed explanation of the principle. Next I will study heap sorting and merge 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.