Algorithms and data structures-introduction and implementation of the sorting Algorithms (C #)

Source: Internet
Author: User
Tags sorts

Sorting refers to arranging the collection of elements in the specified order. There are usually two sorts of sorting methods, ascending and descending. For example, the integer set {5,2,7,1} is sorted in ascending order, the result is {1,2,5,7}, and the result is {7,5,2,1} in descending order. In general, the purpose of sorting is to make the data appear in a more meaningful way. Although the most significant sort of application is arranging data to show it, it can often be used to solve other problems, especially as part of some of the formed algorithms.
In general, sorting algorithms fall into two broad categories: comparison ordering and linear time sequencing. Comparison sorting relies on comparisons and interchanges to move elements to the correct location. Surprisingly, not all sorting algorithms are dependent on comparisons. For algorithms that do rely on comparisons for sorting, they tend to run less often than O (NLG N). For linear time ordering, it can be seen from its name that the running time is often proportional to the number of data elements it processes, i.e. O (n). Unfortunately, linear time ordering relies on certain features in the data set, so we are not able to use it on all occasions. Some sorting algorithms use only the storage space of the data itself to process and output data (these are called in-place sorting), while others require additional space to process and output data (although it may be possible for the final result to be copied into the original memory space).

    <summary>/////Warehousing uncle///Storage Uncles///Source: Some self-write, part of the online excerpt, have been tested can rest assured that use///</summary> public Clas        s Sorthelper {#region public Methods//<summary>///Insert sort///</summary> public static void Insertsort (List<int> List) {/* * complexity O (n^2) * Insert Sort Essentially, one element is taken out of a data set that is never sorted, inserting an ordered set of data. In the implementation shown below, two datasets are stored in data, and data is a connected storage area. Initially, data contains a size unordered element. As Issort runs, data is gradually replaced by an ordered set of data until Issort returns (at this point, data is already an ordered data set).             While the implementation of insertion sequencing uses contiguous storage space, it can also be implemented with linked lists (not all sorts can be implemented using a linked list) and is efficient. */for (int j = 1; j < list. Count;                J + +) {int i = j-1;                int currnet = List[j];                    while (i >= 0 && currnet > list[i]) {list[i + 1] = List[i];                i--;            } list[i + 1] = currnet;      }}///<summary>//Quick Sort  </summary>//<param name= "list" > Target array </param>//<param name= "left" > child table Start Position & lt;/param>//<param name= The end position of the "right" > child table </param> public static void QuickSort (LIST&LT;INT&G T list, int left, int right) {/* * complexity O (nlg^n) * Describes sorting elements in the array data using a quick sort. The number of elements in the array is determined by size. The size of each element is determined by esize. The parameters I and K define the two parts that are currently sorted, and their values are initialized to 0 and size-1, respectively. The function pointer compare points to a user-defined function to compare the element size. Its function function is the same as described in Issort. When Qksort returns, data contains the sorted elements */if (left < right) {int i = Division (list, le                FT, right);                Sort the left part of the pivot QuickSort (list, i + 1, right);            Sort the right part of the pivot QuickSort (list, left, i-1); }}///<summary>///merge sort//</summary>//<param name= "Array" > Target number Group </param>//<param name= "First" > child table starting position </param>//<param name= "LASt "> The terminating position of the child table </param> public static void Mergesortfunction (list<int> array, int first, int. last) The {/* * complexity O (nlg^n) * Description uses the merge sort to sort the elements in the array data. The number of elements in the array is determined by size. The size of each element is determined by esize. The parameters I and K define the two parts that are currently sorted, and their values are initialized to 0 and size-1, respectively. The function pointer compare points to a user-defined function to compare the element size. Its function function is the same as described in Issort.             When Mgsort returns, the data contains the sorted elements.   */if (first < last)//the length of the child table is greater than 1, then go to the following recursive processing {int mid = (first + last)/2;   The Sub-table divides the position mergesortfunction (array, first, mid);    Recursively divide mergesortfunction (array, mid + 1, last) on the left sub-table. Recursively divides the Mergesortcore (array, first, mid, last) into the right sub-table.           Orderly integration of left and right sub-tables (core of merge Sort)}}//<summary>///Count sort///</summary> <param name= "Arraytosort" > Array to sort </param>//<param name= "MaxValue" > Maximum value of the array plus one </ param>///<returns> count after sorting results </returns> public static list<int> Countingsort (list<int> arraya, int arrange) {/* complexity             O (N+k), n is the number of elements to sort, K is the largest integer in data plus 1. * Count ordering is an efficient linear sort that determines how the collection is arranged by calculating the number of occurrences of an element in a collection.              Unlike some of the algorithms described earlier, which are based on comparisons, count ordering does not require an element comparison, and it operates more efficiently than O (NLG N) compared to the efficiency.            */int[] Arrayresult = new Int[arraya.count];            int[] Arraytemp = new Int[arrange + 1];            for (int i = 0; I <= arrange; i++) {arraytemp[i] = 0;            } for (int j = 0; J < Arraya.count; J + +) {Arraytemp[arraya[j]] + = 1;            } for (int k = 1; k <= Arrange; k++) {arraytemp[k] + = arraytemp[k-1]; } for (int m = arraya.count-1; M >= 0; m--) {arrayresult[arraytemp[arraya[m]                ]-1] = arraya[m];            ARRAYTEMP[ARRAYA[M]]-= 1;        } return Arrayresult.tolist (); }        ///<summary>//bubble sort///</summary>//<param name= "arr" ></param> publi c void Ebullitionsort (List<int> arr) {/* * complexity O (n^2) * for 1 to N Records, set in the I-trip sort Flag Flag:=true, unsorted flag. Scan from bottom to top, j as the inner loop variable, make n-i comparison. In the J-trip comparison, if R[J+1]&LT;R[J] is exchanged, and the flag is false.             At the end of a trip, if flag is true, the sort is terminated.            */int I, j, temp;            bool done = false;            j = 1; while (J < arr.                Count) && (!done)//judgment length {done = true; for (i = 0; i < arr. Count-j; i++) {if (Arr[i] > arr[i + 1]) {done = FA                        Lse                        temp = Arr[i];                    Arr[i] = arr[i + 1];//Exchange data arr[i + 1] = temp;            }} j + +;      }} #endregion #region Private Methods  <summary>///merge the core of the sort: two ordered left and right sub-tables (in mid), merged into an ordered table////</summary>//<param N Ame= "Array" ></param>//<param name= "First" ></param>//<param name= "mid" ></ param>//<param name= "Last" ></param> private static void Mergesortcore (List<int> arra   Y, int first, int mid, int last) {int indexa = first;//left child table start position int INDEXB = mid + 1; Start position of the right child table int[] Temp = new Int[last + 1];            Declares an array (staging all ordered columns of the left and right child tables): The length equals the sum of the left and right child tables.            int tempindex = 0; while (Indexa <= mid && indexb <= last)//to traverse the left and right sub-tables, if one of the child tables is traversed, the loop {if (array [Indexa] <= ARRAY[INDEXB])//At this time Zoozi number of <= right child table number {temp[tempindex++] = array[indexa++    ]; Places the number of left child tables in the staging array, traversing the left sub-table subscript + +} else//the number of Zoozi at this time > number of Right child table {TEM P[tempindex++] = array[indexb++]; Put the number of right child table in the staging array, traverse right sub-table subscript + +}}//Have one side of the child table after the completion, jump out of the loop, the other side of the remaining child table once placed in the staging array (ordered) WH            Ile (Indexa <= mid) {temp[tempindex++] = array[indexa++];            } while (Indexb <= last) {temp[tempindex++] = array[indexb++];            }//To write the ordered sequence of columns in the staging array to the set position of the target array, so that the sorted array segment is ordered Tempindex = 0;            for (int i = First, I <= last; i++) {array[i] = temp[tempindex++]; }}///<summary>///Get the pivot position by pivot value///</summary>//<param name= "l Ist "></param>//<param name=" left "></param>//<param name=" right "></param&        Gt             <returns></returns> private static int division (list<int> List, int left, int. right) {                while (left < right) {int num = List[left];                    Use the first element as the pivot if (num > list[left + 1]) {List[left] = list[left + 1];                    List[left + 1] = num;                left++;                    } else {int temp = List[right];                    List[right] = list[left + 1];                    List[left + 1] = temp;                right--; }} return left; The position of the pivot at this point} #endregion}

Algorithms and data structures-introduction and implementation of the sorting Algorithms (C #)

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.