Large summary of sorting algorithms

Source: Internet
Author: User

Large summary of sorting algorithms
Sorting algorithm is the most basic and most commonly used algorithms, but also the major listed companies will often be asked to interview the knowledge Point, different sorting algorithms in different scenarios or applications will have different performance, we need to be skilled in a variety of sorting algorithms to apply it to the actual application, in order to better play their advantages,      So today we have a simple summary and analysis of the various algorithms. Bubble sort

The bubble sort is to move the small element forward or the large element back. The comparison is an adjacent two element comparison, and the interchange also occurs between these two elements. Therefore, if the two elements are equal, we will not be bored to exchange them, if the two equal elements are not adjacent, then even through the preceding 22 exchange two adjacent together, this time will not be exchanged, so the same elements of the order has not changed, so bubble sort is a stable sorting algorithm. "Bubble sort is the most classic sorting algorithm, it is based on the comparison of sorting algorithm, time complexity of O (n^2), the advantages are simple implementation, n smaller performance is better." 】

Algorithm principle:

  • Adjacent data for 22 comparison, decimals placed in front, large number in the back, such a trip down, the smallest number is ranked first, the second trip is so, and so on, until all the data sort is done

  • C + + code implementation:     
    void Bubble_sort (int arr[], int len) {for      (int i = 0; i < len-1; i++)      {for          (int j = len-1; J >= I; j--)          {              if (Arr[j] < arr[j-1])              {                  int temp = arr[j];                  ARR[J] = arr[j-1];                  ARR[J-1] = temp;}}}}      
    Select sort     

    Select Sort is the smallest of the current elements selected for each location, such as selecting the smallest one for the first position, selecting the second small for the second element in the remaining elements, and so on, until then-1Element, sectionNElement is not selected, because it is only one of the largest elements left. Then, in a trip, if the current element is smaller than an element, and the small element appears behind an element that is equal to the current element, then the post-swap stability is destroyed. A bit of a mouthful, for example, a sequence5 8 5) 2 9, We know the first time to select1An element5Will and2Exchange, then in the original sequence2A5The relative order is destroyed, so choosing a sort is not a stable sorting algorithm. "This sorting method is the sorting algorithm of the switching method, and the efficiency isO (n2)。 In the actual application is in and bubble sort basically same position. They are just the initial stages of the development of sorting algorithms, which are less used in practice.

    Algorithm principle:

  • Finds the smallest (large) element in an unordered sequence, stores it at the starting position of the sort sequence, and then continues to look for the smallest (large) element from the remaining unsorted elements, and then places it at the end of the sorted sequence. And so on until all elements are sorted.
  • C + + code implementation:
    void Select_sort (int arr[], int len)  {for      (int i = 0; i < len; i++)      {          int index = i;          for (int j = i + 1; j < Len; j + +)          {              if (Arr[j] < Arr[index])                  index = j;          }          if (Index! = i)          {              int temp = arr[i];              Arr[i] = Arr[index];              Arr[index] = temp;}}  }
    Insert Sort 

    An insert sort is an element that is inserted one at a time, based on an already ordered small sequence. Of course, there are only 1 elements at the beginning of this ordered sequence, which is the first element. The comparison starts at the end of the ordered sequence, that is, the element that you want to insert and the one that is already in order, is inserted directly behind it if it is larger than it is, or until it is found where it is inserted. If you encounter an element equal to the insert, the insertion element places the element you want to insert behind the equal element. So, the order of the equal elements is not changed, the order from the original unordered sequence is the order of the sequence, so the insertion sort is stable. "Insert sort by inserting the values in a sequence into a sorted sequence until the end of the sequence. Insert sort is an improvement to the bubbling sort. It's 2 times faster than bubble sort. It is generally not necessary to use an insert sort when the data is greater than $ , or to repeat the sequence of more than a data item. 】

    Algorithm principle:

  • divides the data into two parts, an ordered part and an unordered part, the first ordered part contains the 1th element, and sequentially inserts the unordered element into the ordered part until all elements are ordered. Insert sort is divided into direct insert sort, binary insert sort, linked list insert, etc., here only the direct insertion sort is discussed. It is a stable sorting algorithm with a time complexity of O (n^2)
  • C + + code implementation:
    void Insert_sort (int arr[], int len)  {for      (int i = 1; i < Len; i + +)      {          int j = i-1;          int k = Arr[i];          while (J >-1 && k < arr[j])          {              arr[j + 1] = Arr[j];              J--;          }          Arr[j + 1] = k;      }  }

    Quick Sort    

        The quick sort has two directions, the left oneISubscript always go right, whenA[i] <= A[center_index], whereCenter_indexis an array subscript for the central element, usually taken as0An element. And on the right.JThe subscript always goes left, whenA[j] > A[center_index]。 IfIAndJCan't move,I <= J,ExchangeA[i]AndA[j],Repeat the process above untili>j。ExchangeA[j]AndA[center_index], complete a quick sort of trip. In the central element andA[j]In exchange, it is possible to disrupt the stability of the preceding elements, such as the sequence listed5 3 3 4 3 8 9, Now the central element5And3 (The5Elements, subscript from1Start Count)The exchange will take the element3Stability is disrupted, so fast sequencing is an unstable sorting algorithm that occurs in the central element andA[j]Exchange of time. 【fast sorting is faster than most sorting algorithms. Although we can write algorithms that are faster than fast sorting in some special cases, there is usually no faster than that. Fast sorting is recursive, and it is not a good choice for machines with very limited memory.

    Algorithm principle:

  • Fast sequencing is a very efficient sorting algorithm in practice, it is not a stable sorting algorithm, the average time complexity is O (NLOGN), the worst case complexity is O (n^2). 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.
  • C + + code implementation:
    void Quick_sort (int arr[], int left, int. right) {  if (left < right)  {      int i = left, j = right, target = arr[ Left];      while (I < j)      {          while (i < J && Arr[j] > target)              j--;          if (i < J)              arr[i++] = arr[j];          while (I < J && Arr[i] < target)              i++;          if (i < J)              arr[j] = Arr[i];      }      Arr[i] = target;      Quick_sort (arr, left, i-1);      Quick_sort (arr, i + 1, right);  }}

    Merge sort

    Merge sort is to divide the sequence recursively into short sequences, and the recursive exits are short sequences with only1An element(Think Direct and orderly)Or2A sequence(1Times comparison and exchange),Then the ordered sequence of segments is combined into an ordered long sequence, which is continuously merged until the original sequence is fully sequenced. Can be found, in1One or2An element,1Elements are not exchanged,2Elements, if they are equal in size, are not exchanged intentionally, which does not undermine stability. So, in the process of merging short ordered sequences, is stability compromised? No, we can guarantee that if the two current elements are equal, we keep the elements in the preceding sequence in front of the result sequence, which guarantees stability. Therefore, the merge sort is also a stable sorting algorithm. The merge sort first decomposes the sequence to be sorted, from1Into2,2Into4, decompose in turn, when decomposed into only1Group, you can sort the groupings and then merge them back into the original sequence so that all the data can be sorted. A merge sort is slightly faster than a heap sort, but requires more memory space than the heap, because it requires an extra array. 】

    Algorithm principle:

  • Merge sort works as follows (assuming that the sequence has n elements):

    • Merges each contiguous two digits of a sequence (merge) into a floor (N/2) sequence with two elements for each sequence
    • Merge the above sequence again to form a floor (N/4) sequence with four elements per sequence
    • Repeat step 2 until all elements are sorted

      Merge sort is a stable sorting algorithm, its time complexity is O (NLOGN), if the implementation of the linked list, the spatial complexity can reach O (1), but if the use of arrays to store data, in the process of merging, the need for temporary space to store the merged good data, so the spatial complexity of O (n)


  • void merge (int arr[], int temp_arr[], int start_index, int mid_index, int end_index) {int i = Start_index, j = mid_      Index + 1;      int k = 0; while (I < Mid_index + 1 && J < End_index + 1) {if (Arr[i] > arr[j]) temp_arr          [k++] = arr[j++];      else temp_arr[k++] = arr[i++];      } while (I < Mid_index + 1) {temp_arr[k++] = arr[i++];      } while (J < End_index + 1) temp_arr[k++] = arr[j++];  for (i = 0, j = start_index; J < End_index + 1; i + +, J + +) Arr[j] = Temp_arr[i];      } void Merge_sort (int arr[], int temp_arr[], int start_index, int end_index) {if (Start_index < End_index)          {int Mid_index = (Start_index + end_index)/2;          Merge_sort (arr, Temp_arr, Start_index, Mid_index);          Merge_sort (arr, Temp_arr, Mid_index + 1, end_index);      Merge (arr, Temp_arr, Start_index, Mid_index, End_index); }  }


    Heap Sort    

       We know that the structure of the heap is a nodeIThe child for2*iAnd2*i+1node, the large top heap requires the parent node to be greater than or equal to its2Child nodes, the small top heap requires that the parent node is less than or equal to its2Child nodes. In a long-NSequence, the process of sorting the heap is from the firstN/2Start and its child nodes are all3Values to select the maximum number of(Big Top Pile)or minimum(Small Top Pile),This3The choice between elements is of course not to undermine stability. But when it isn/2-1, N/2-2, ... 1When these parent nodes select an element, the stability is broken. It is possible that the firstN/2A parent node Exchange passes the latter element, and the firstn/2-1A parent node does not exchange the following same element, then this2The stability between the same elements is destroyed. So, heap sorting is not a stable sorting algorithm. "the time complexity of heap sequencing is O (NLOGN)"

    Heap Storage      is typically an array to store the heap, iThe node's parent node subscript is (i – 1) / 2. Its left and right sub-nodes are labeled 2 * i + 1and the 2 * i + 2. such as the No. 0 node of the left and right sub-nodes subscript 1 and 2 respectively. Storage structure:       

    Algorithm principle:

  • First the initial data R[1..N] is built into a maximum heap, which is the initial unordered area
  • Then the largest record of the keyword R[1] (that is, the heap top) and the last record of the unordered zone R[n] exchange, resulting in a new unordered area r[1..n-1] and ordered area R[n], and meet R[1..n-1].keys≤r[n].key
  • Because the new root r[1] may violate the heap nature, the current unordered area r[1..n-1] should be adjusted to a heap.
  • Repeat steps 2 and 3 until there is only one element in the unordered area.
  • C + + code implementation:
    /** * Set the array arr to build a large heap * @param arr to adjust the array * @param i the subscript of the array element to be adjusted * @param len array length */void heap_adjust (int arr[], int i, int    Len) {int child;    int temp;  for (; 2 * i + 1 < len; i = child) {Child = 2 * i + 1; Location of the child node = 2 * Parent node position + 1//Get node with greater key value in sub-node if (Child < len-1 && Arr[child + 1] > Arr[child]        ) Child + +;            If the larger child node is larger than the parent node, move the larger child node upward, replacing its parent node if (Arr[i] < Arr[child]) {temp = Arr[i];            Arr[i] = Arr[child];        Arr[child] = temp;    } else break;    }}/** * Heap Sorting algorithm */void heap_sort (int arr[], int len) {int i;    Adjusts the first half of the sequence of elements, after adjusting the element is the largest element of the sequence for (int i = LEN/2-1; I >= 0; i--) {heap_adjust (arr, I, Len); } for (i = len-1; i > 0; i--) {//swaps the 1th element with the current last element, guaranteeing that the current last position of the element is now the largest int temp = Arr[0 in this sequence.        ];        Arr[0] = Arr[i];        Arr[i] = temp;   Continuously reduce the range of the adjustment heap to ensure that the first element is the maximum value of the current sequence at each adjustment     Heap_adjust (arr, 0, I); }}


    Summary: Analysis of the above various sorting algorithms, the following table summarizes the characteristics of various sorting algorithms, such as:

    OK, learning this is not feel oneself and enrich a lot of, then continue to refuel it!



    Large summary 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.