This issue is the 15th section of C + + basic syntax sharing. Today, let's sort out the top five of the top ten sorting algorithms!
Bubble sorting
Bubble sorting idea:
1. Compare adjacent elements. If the first one is bigger than the second, exchange them.
2. Do the same work for each pair of adjacent elements, from the first pair at the beginning to the last pair at the end. After this step, the last element will be the maximum number.
3. Repeat the above steps for all elements except the last one.
4. Continue to repeat the above steps for fewer and fewer elements each time until there is no pair of numbers to compare.
Example:
// Bubble sorting void BubbleSort(vector<int>& v) { int len = v.size(); for (int i = 0; i < len - 1; ++i) for (int j = 0; j < len - 1 - i; ++j) if (v[j] > v[j + 1]) swap(v[j], v[j + 1]); } // Template implementation bubble sorting template<typename T> //Integer or floating-point numbers can be used. To use object (class), operator function greater than (>) must be set void bubble_sort(T arr[], int len) { for (int i = 0; i < len - 1; i++) for (int j = 0; j < len - 1 - i; j++) if (arr[j] > arr[j + 1]) swap(arr[j], arr[j + 1]); } // Bubble sorting (improved version) void BubbleSort_orderly(vector<int>& v) { int len = v.size(); bool orderly = false; for (int i = 0; i < len - 1 && !orderly; ++i) { orderly = true; for (int j = 0; j < len - 1 - i; ++j) { if (v[j] > v[j + 1]) { // from small to large orderly = false; // Exchange is still unordered swap(v[j], v[j + 1]); } } } }
Select sort
Select Sorting idea:
1. Find the smallest (largest) element in the unordered sequence and store it at the beginning of the sorted sequence
2. Continue to find the smallest (large) element from the remaining unordered elements, and then put it at the end of the sorted sequence
3. Wait until all elements are sorted
Example:
void SelectionSort(vector<int>& v) { int min, len = v.size(); for (int i = 0; i < len - 1; ++i) { min = i; for (int j = i + 1; j < len; ++j) { if (v[j] < v[min]) { // Mark the smallest min = j; } } if (i != min) // Swap to the front swap(v[i], v[min]); } } // Template implementation template<typename T> void Selection_Sort(std::vector<T>& arr) { int len = arr.size(); for (int i = 0; i < len - 1; i++) { int min = i; for (int j = i + 1; j < len; j++) if (arr[j] < arr[min]) min = j; if(i != min) std::swap(arr[i], arr[min]); } }
Insert sort
Insert sorting idea:
1. Starting from the first element, the element can be considered to have been sorted
2. Take out the next element and scan from back to front in the sorted element sequence
3. If the element (sorted) is larger than the new element, move the element to the next position
4. Repeat step 3 until the sorted element is found to be less than or equal to the new element
5. After inserting the new element into this position
6. Repeat steps 2 to 5
Example:
// Insert sort void InsertSort(vector<int>& v) { int len = v.size(); for (int i = 1; i < len; ++i) { int temp = v[i]; for(int j = i - 1; j >= 0; --j) { if(v[j] > temp) { v[j + 1] = v[j]; v[j] = temp; } else break; } } }
Quick sort
Quick sort idea:
1. Select the first number as the benchmark
2. Swap the number smaller than the benchmark to the front and the number larger than the benchmark to the back
3. Repeat the second step for the left and right intervals until there is only one number in each interval
// Quick sort (recursive) void QuickSort(vector<int>& v, int low, int high) { if (low >= high) // End flag return; int first = low; // Low subscript int last = high; // High subscript int key = v[first]; // Set the first as the benchmark while (first < last) { // Move the smaller than the first one to the front while (first < last && v[last] >= key) last--; if (first < last) v[first++] = v[last]; // Move the larger than the first one to the back while (first < last && v[first] <= key) first++; if (first < last) v[last--] = v[first]; } // Reference setting v[first] = key; // First half recursion QuickSort(v, low, first - 1); // Second half recursion QuickSort(v, first + 1, high); } // ---------------------------------------------------- // Template for quick sorting (recursive) template <typename T> void quick_sort_recursive(T arr[], int start, int end) { if (start >= end) return; T mid = arr[end]; int left = start, right = end - 1; while (left < right) { while (arr[left] < mid && left < right) left++; while (arr[right] >= mid && left < right) right--; std::swap(arr[left], arr[right]); } if (arr[left] >= arr[end]) std::swap(arr[left], arr[end]); else left++; quick_sort_recursive(arr, start, left - 1); quick_sort_recursive(arr, left + 1, end); } template <typename T> //Integer or floating-point numbers can be used. If you want to use an object (class), you must set the operator functions of "less than" (<), "greater than" (>), "not less than" (> =) void quick_sort(T arr[], int len) { quick_sort_recursive(arr, 0, len - 1); } // ---------------------------------------------------- // Template implementation quick sort (iteration) struct Range { int start, end; Range(int s = 0, int e = 0) { start = s, end = e; } }; template <typename T> // Integer or floating-point numbers can be used. If you want to use an object (class), you must set the operator functions of "less than" (<), "greater than" (>), "not less than" (> =) void quick_sort(T arr[], const int len) { if (len <= 0) return; // Avoid declaring the stack array crash when len is equal to a negative value // r [] simulates stacking, p is quantity, r[p + +] is push,r[--p] is pop and obtains elements Range r[len]; int p = 0; r[p++] = Range(0, len - 1); while (p) { Range range = r[--p]; if (range.start >= range.end) continue; T mid = arr[range.end]; int left = range.start, right = range.end - 1; while (left < right) { while (arr[left] < mid && left < right) left++; while (arr[right] >= mid && left < right) right--; std::swap(arr[left], arr[right]); } if (arr[left] >= arr[range.end]) std::swap(arr[left], arr[range.end]); else left++; r[p++] = Range(range.start, left - 1); r[p++] = Range(left + 1, range.end); } }
Heap sort
Heap sorting: (maximum heap, ordered area). Unload the root from the top of the heap and put it in the orderly area before restoring the heap.
#include <iostream> #include <algorithm> using namespace std; // Heap sorting: (maximum heap, ordered area). Unload the root from the top of the heap and put it in the orderly area before restoring the heap. void max_heapify(int arr[], int start, int end) { //Create parent node indicators and child node indicators int dad = start; int son = dad * 2 + 1; while (son <= end) { //Only when the sub node indicators are within the range can they be compared if (son + 1 <= end && arr[son] < arr[son + 1]) //First, compare the size of the two child nodes and select the largest one son++; if (arr[dad] > arr[son]) //If the parent node is larger than the child node, it means that the adjustment is completed, and the function will jump out directly return; else { //Otherwise, exchange the parent-child content, and then continue the comparison between child nodes and grandchildren swap(arr[dad], arr[son]); dad = son; son = dad * 2 + 1; } } } void heap_sort(int arr[], int len) { //Initialization, i starting from the last parent node for (int i = len / 2 - 1; i >= 0; i--) max_heapify(arr, i, len - 1); //First, exchange the first element with the previous element that has been arranged, and then adjust it again (the element before the element just adjusted) until sorting is completed for (int i = len - 1; i > 0; i--) { swap(arr[0], arr[i]); max_heapify(arr, 0, i - 1); } } int main() { int arr[] = { 3, 5, 3, 0, 8, 6, 1, 5, 8, 6, 2, 4, 9, 4, 7, 0, 1, 8, 9, 7, 3, 1, 2, 5, 9, 7, 4, 0, 2, 6 }; int len = (int) sizeof(arr) / sizeof(*arr); heap_sort(arr, len); for (int i = 0; i < len; i++) cout << arr[i] << ' '; cout << endl; return 0; }
That's all for today's sharing. We should learn C + + well~
Write at the end: for those who are ready to learn C/C + + programming, if you want to better improve your core programming ability (internal skill), you might as well start now!
C language c + + programming learning and communication circle, QQ group: 904329806[ Click to enter WeChat official account: C language programming learning base
Sorting and sharing (source code, project practice video, project notes, basic introductory tutorial)
Welcome to change careers and learn programming partners. Use more materials to learn and grow faster than you think!
Sharing of programming learning books:
Programming learning video sharing: