A simple sorting algorithm that repeatedly steps through the list, compares adjacent elements and swaps them if they are in the wrong order. It has a worst-case and average-case time complexity of O(n^2).
voidbubble_sort(vector<int>& arr){ for (int i = 0; i < arr.size() - 1; i++) { // EACH ROUND WILL MOVE THE LARGEST ELEMENT TO THE LAST for (int j = 0; j < arr.size() - 1 - i; j++) { if (arr[j] > arr[j + 1]) { // SWAP arr[j] and arr[j + 1] int tmp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = tmp; } } } }
A simple sorting algorithm that repeatedly selects the minimum element from the unsorted portion of the list and swaps it with the leftmost unsorted element. It has a worst-case and average-case time complexity of O(n^2).
A divide-and-conquer algorithm that recursively divides the input list into two halves, sorts each half, and then merges the sorted halves back together. It has a worst-case and average-case time complexity of O(n log n).
A divide-and-conquer algorithm that recursively partitions the input list into two sub-lists based on a pivot element, and then sorts each sub-list. It has a worst-case time complexity of O(n^2), but an average-case time complexity of O(n log n).
A sorting algorithm that uses a binary heap data structure to repeatedly extract the maximum element from the heap and place it at the end of the sorted array. It has a worst-case and average-case time complexity of O(n log n).
voidheapify(vector<int>& arr, int n, int i){ int largest = i; int left = 2 * i + 1; int right = 2 * i + 2; if (left < n && arr[left] > arr[largest]) { largest = left; } if (right < n && arr[right] > arr[largest]) { largest = right; } if (largest != i) { swap(arr[i], arr[largest]); heapify(arr, n, largest); } }
voidheap_sort(vector<int>& arr){ int n = arr.size(); for (int i = n / 2 - 1; i >= 0; i--) { heapify(arr, n, i); } for (int i = n - 1; i >= 0; i--) { swap(arr[0], arr[i]); heapify(arr, i, 0); } }