Summary of various sorting algorithms

Summary of various sorting algorithms

Sorting algorithms are the most basic and commonly used algorithms. Different sorting algorithms will have different performances in different scenarios or applications. We need to be proficient in various sorting algorithms to apply them in practice and to better play their advantages. Today, let's summarize various sorting algorithms.

The following table summarizes the complexity and stability of various sorting algorithms:

Comparison of the complexity of various sorting algorithms.png

Bubble Sort

Bubble sort is the most classic sorting algorithm. It is a comparison-based sorting algorithm with a time complexity of O(n^2). Its advantages are simple implementation and better performance when n is small.

  • Algorithm principle: Adjacent data are compared in pairs, with small numbers placed in front and large numbers placed in the back. After one round, the smallest number is ranked first, and the second round is the same, and so on, until all the data is sorted.

  • C++ code implementation

  1. void bubble_sort( int arr[], int len)
  2. {
  3. for ( int i = 0 ; i < len - 1 ; i++)
  4. {
  5. for ( int j = len - 1 ; j >= i; j--)
  6. {
  7. if (arr[j] < arr[j - 1 ])
  8. {
  9. int temp = arr[j];
  10. arr[j] = arr[j - 1 ];
  11. arr[j - 1 ] = temp;
  12. }
  13. }
  14. }
  15. }

Selection Sort

  • The algorithm works by first finding the smallest (largest) element in the unsorted sequence and storing it at the beginning of the sorted sequence. Then, continue to find the smallest (largest) element from the remaining unsorted elements and place it at the end of the sorted sequence. This process continues until all elements are sorted.
  • C++ code implementation

  1. void select_sort( int arr[], int len)
  2. {
  3. for ( int i = 0 ; i < len; i++)
  4. {
  5. int index = i;
  6. for ( int j = i + 1 ; j < len; j++)
  7. {
  8. if (arr[j] < arr[index])
  9. index = j;
  10. }
  11. if (index != i)
  12. {
  13. int temp = arr[i];
  14. arr[i] = arr[index];
  15. arr[index] = temp;
  16. }
  17. }
  18. }

Insertion Sort

  • The algorithm principle divides the data into two parts, the ordered part and the unordered part. At the beginning, the ordered part contains the first element, and the unordered elements are inserted into the ordered part in sequence until all elements are in order. Insertion sort is divided into direct insertion sort, binary insertion sort, linked list insertion, etc. Here we only discuss direct insertion sort. It is a stable sorting algorithm with a time complexity of O(n^2)
  • C++ code implementation

  1. void insert_sort( int arr[], int len)
  2. {
  3. for ( int i = 1 ; i < len; i ++)
  4. {
  5. int j = i - 1 ;
  6. int k = arr[i];
  7. while (j > - 1 && k < arr[j] )
  8. {
  9. arr[j + 1 ] = arr[j];
  10. j --;
  11. }
  12. arr[j + 1 ] = k;
  13. }
  14. }

Quick Sort

  • Algorithm principle Quick sort is a very efficient sorting algorithm in practice. It is not a stable sorting algorithm. The average time complexity is O(nlogn) and the complexity is O(n^2) in the worst case. Its basic idea is to divide the data to be sorted into two independent parts through a sorting process, where all the data in one part is smaller than all the data in the other part. Then, the two parts of data are quickly sorted separately according to this method. The whole sorting process can be performed recursively to turn the whole data into an ordered sequence.
  • C++ code implementation

  1. void quick_sort( int arr[], int left, int right)
  2. {
  3. if (left < right)
  4. {
  5. int i = left, j = right, target = arr[left];
  6. while (i < j)
  7. {
  8. while (i < j && arr[j] > target)
  9. j--;
  10. if (i < j)
  11. arr[i++] = arr[j];
  12.  
  13. while (i < j && arr[i] < target)
  14. i++;
  15. if (i < j)
  16. arr[j] = arr[i];
  17. }
  18. arr[i] = target;
  19. quick_sort(arr, left, i - 1 );
  20. quick_sort(arr, i + 1 , right);
  21. }
  22. }

Merge Sort

  • Algorithm principle The specific working principle of merge sort is as follows (assuming that the sequence has a total of n elements):

    • Merge every two adjacent numbers in the sequence to form floor(n/2) sequences. After sorting, each sequence contains two elements.
    • Merge the above sequences again to form floor(n/4) sequences, each containing four elements
    • Repeat step 2 until all elements are sorted.

      Merge sort is a stable sorting algorithm with a time complexity of O(nlogn). If a linked list is used, the space complexity can reach O(1). However, if an array is used to store data, temporary space is required to store the merged data during the merging process, so the space complexity is O(n).

  • C++ code implementation

  1. void merge( int arr[], int temp_arr[], int start_index, int mid_index, int end_index)
  2. {
  3. int i = start_index, j = mid_index + 1 ;
  4. int k = 0 ;
  5. while (i < mid_index + 1 && j < end_index + 1 )
  6. {
  7. if (arr[i] > arr[j])
  8. temp_arr[k++] = arr[j++];
  9. else  
  10. temp_arr[k++] = arr[i++];
  11. }
  12. while (i < mid_index + 1 )
  13. {
  14. temp_arr[k++] = arr[i++];
  15. }
  16. while (j < end_index + 1 )
  17. temp_arr[k++] = arr[j++];
  18.  
  19. for (i = 0 , j = start_index; j < end_index + 1 ; i ++, j ++)
  20. arr[j] = temp_arr[i];
  21. }
  22.  
  23. void merge_sort( int arr[], int temp_arr[], int start_index, int end_index)
  24. {
  25. if (start_index < end_index)
  26. {
  27. int mid_index = (start_index + end_index) / 2 ;
  28. merge_sort(arr, temp_arr, start_index, mid_index);
  29. merge_sort(arr, temp_arr, mid_index + 1 , end_index);
  30. merge(arr, temp_arr, start_index, mid_index, end_index);
  31. }
  32. }

Heap Sort

Binary Heap

A binary heap is a complete binary tree or an approximately complete binary tree that satisfies two properties.

  • The key value of the parent node is always greater than or equal to (less than or equal to) the key value of any child node
  • The left subtree and right subtree of each node are a binary heap

When the key value of the parent node is always greater than or equal to the key value of any child node, it is a maximum heap. When the key value of the parent node is always less than or equal to the key value of any child node, it is a minimum heap. Generally, a binary tree is simply called a heap.

Heap storage

Generally, an array is used to store a heap. The parent node of node i has a subscript of (i – 1) / 2. The subscripts of its left and right child nodes are 2 * i + 1 and 2 * i + 2 respectively. For example, the subscripts of the left and right child nodes of node 0 are 1 and 2 respectively. The storage structure is shown in the figure:

Heap structure.png

Heap sort principle

The time complexity of heap sort is O(nlogn)

  • Algorithm principle (taking *** heap as an example)

    • First, build the initial data R[1..n] into a *** heap, which is the initial unordered area
    • Then swap the record R[1] (i.e. the top of the heap) with the last record R[n] in the unordered area, thus obtaining a new unordered area R[1..n-1] and an ordered area R[n], and satisfying R[1..n-1].keys≤R[n].key
    • Since the new root R[1] after the swap may violate the heap property, 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 region.
  • C++ code implementation

  1. /**
  2. * Build a large root heap from array arr
  3. * @param arr the array to be adjusted
  4. * @param i The subscript of the array element to be adjusted
  5. * @param len the length of the array
  6. */  
  7. void heap_adjust( int arr[], int i, int len)
  8. {
  9. int child;
  10. int temp;
  11.  
  12. for (; 2 * i + 1 < len; i = child)
  13. {
  14. child = 2 * i + 1 ; // child node position = 2 * parent node position + 1  
  15. // Get the node with the larger key value among the child nodes  
  16. if (child < len - 1 && arr[child + 1 ] > arr[child])
  17. child++;
  18. // If the larger child node is larger than the parent node, move the larger child node up and replace its parent node  
  19. if (arr[i] < arr[child])
  20. {
  21. temp = arr[i];
  22. arr[i] = arr[child];
  23. arr[child] = temp;
  24. }
  25. else  
  26. break ;
  27. }
  28. }
  29.  
  30. /**
  31. * Heap sort algorithm
  32. */  
  33. void heap_sort( int arr[], int len)
  34. {
  35. int i;
  36. // Adjust the first half of the sequence so that the last element is the last element in the sequence  
  37. for ( int i = len / 2 - 1 ; i >= 0 ; i--)
  38. {
  39. heap_adjust(arr, i, len);
  40. }
  41.  
  42. for (i = len - 1 ; i > 0 ; i--)
  43. {
  44. // Swap the first element with the last element to ensure that the last element in the current sequence is the first one  
  45. int temp = arr[ 0 ];
  46. arr[ 0 ] = arr[i];
  47. arr[i] = temp;
  48. // Keep reducing the range of the heap, and ensure that the first element is the maximum value of the current sequence after each adjustment  
  49. heap_adjust(arr, 0 , i);
  50. }
  51. }

<<:  A brief analysis of the five common mistakes made by independent game CPs

>>:  How to teach your girlfriend programming?

Recommend

App Store Data Analysis for APP Promotion

There is a lot of data in the App Store, but for ...

What are the advantages of developing WeChat mini-programs for lawyers?

As a legal citizen, we must not only learn to abi...

Make intelligence simpler and teach you how to use Xiaomi TV 2 Elderly Mode

At present, many technological products are insep...

We use coupons every day, but what exactly are coupons?

Because of my work, I have been dealing with coup...

All-round upgrade! Beidou has a new update after a thousand days!

At 10:49 on May 17, my country successfully launc...

The internationalization of Chinese home appliances is mostly forced

What is the overseas gold rush, broad prospects, ...

If your body has these 4 symptoms, it means you are very healthy!!!

References [1] Keendjele TPT, Eelu HH, Nashihanga...

Teach you how to open the Douyin "product showcase" step by step

There are three ways to monetize Douyin: product ...

The cutest wrestling showdown TV version of "Run, Sheep" fun experience

Screen: Sound Effects: operate: Plot: Experience:...

Is the spring for “black taxis” coming?

It's easy to hate a city when you're in a...