Advertisement
Coder_22

Sorting

Jul 26th, 2023
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.56 KB | None | 0 0
  1. Merge Sort:
  2. Complexity: O(n*log(n))
  3.  
  4. void merge(int l, int r, int mid, vector<int> &v) {
  5.     int l_sz = mid - l + 1;
  6.     vector<int> L(l_sz + 1);
  7.     int r_sz = r - mid;
  8.     vector<int> R(r_sz + 1);
  9.     for(int i = 0; i < l_sz; ++i) L[i] = v[i+l];
  10.     for(int i = 0; i < r_sz; ++i) R[i] = v[i+mid+1];
  11.     L[l_sz] = R[r_sz] = INT_MAX;
  12.     int l_i = 0, r_i = 0;
  13.     for(int i = l; i <= r; ++i) {
  14.         if(L[l_i] <= R[r_i]) v[i] = L[l_i++];
  15.         else v[i] = R[r_i++];
  16.     }
  17. }
  18. void msrt(int l, int r, vector<int> &v) {
  19.     if(l == r) return;
  20.     int mid = (l + r) >> 1;
  21.     msrt(l, mid, v);
  22.     msrt(mid + 1, r, v);
  23.     merge(l, r, mid, v);
  24. }
  25.  
  26. Quick Sort:
  27.  
  28. Complexity: O(n*log(n))
  29.  
  30. int partition(int arr[], int low, int high) {
  31.     int pivot = arr[high];
  32.     int i = (low - 1);
  33.     for (int j = low; j <= high - 1; j++) {
  34.         if (arr[j] < pivot) swap(arr[++i], arr[j]);
  35.     }
  36.     swap(arr[i + 1], arr[high]); return (i + 1);
  37. }
  38. void quickSort(int arr[], int low, int high) {
  39.     if (low < high) {
  40.         int pi = partition(arr, low, high);
  41.         quickSort(arr, low, pi - 1);
  42.         quickSort(arr, pi + 1, high);
  43.     }
  44. }
  45.  
  46. Heap Sort:
  47. Complexity: O(n*log(n))
  48.  
  49. void heapify(int ar[], int n, int i) {
  50.     int mx = i, l = (i << 1) + 1, r = (i << 1) + 2;
  51.     if (l < n && ar[l] > ar[mx]) mx = l;
  52.     if (r < n && ar[r] > ar[mx]) mx = r;
  53.     if (mx != i) {
  54.         swap(ar[i], ar[mx]);
  55.         heapify(ar, n, mx);
  56.     }
  57. }
  58. void hsrt(int ar[], int n) {
  59.     for (int i = (n >> 1) - 1; i >= 0; --i)
  60.         heapify(ar, n, i);
  61.     for (int i = n - 1; i > 0; --i) {
  62.         swap(ar[0], ar[i]);
  63.         heapify(ar, i, 0);
  64.     }
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement