Imran_Mohammed

Sorting

Jan 31st, 2022 (edited)
442
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.99 KB | None | 0 0
  1. //#################Merge Sort : ##################
  2. #include <bits/stdc++.h>
  3. using namespace std;
  4.  
  5. int a[11] = { 10, 14, 19, 26, 27, 31, 33, 35, 42, 44, 0 };
  6.     int b[11];
  7.  
  8. void merging(int low, int mid, int high) {
  9.    int i=low,j=mid+1,k=low;
  10.  
  11.    while(i<=mid && j<=high){
  12.     if(a[i] <= a[j]){
  13.         b[k] = a[i];
  14.         i++;
  15.         k++;
  16.     }
  17.  
  18.     else{
  19.         b[k] = a[j];
  20.         j++;
  21.         k++;
  22.     }
  23.  
  24.    }
  25.  
  26.    //Another element if there
  27.    if(i>mid){
  28.     while(j<=high){
  29.         b[k] = a[j];
  30.         j++;
  31.         k++;
  32.     }
  33.    }
  34.  
  35.    else{
  36.     while(i<=mid){
  37.         b[k] = a[i];
  38.         i++;
  39.         k++;
  40.     }
  41.    }
  42.  
  43.    //Copy temporary array to original array:
  44.    for(k=low; k<=high; k++){
  45.     a[k] = b[k];
  46.    }
  47.  
  48. }
  49.  
  50. void so_rt(int low, int high) {
  51.    int mid;
  52.  
  53.    if(low < high) {
  54.       mid = (low + high) / 2;
  55.       so_rt(low, mid);
  56.       so_rt(mid+1, high);
  57.       merging(low, mid, high);
  58.    }
  59.  
  60.    else {
  61.       return;
  62.    }
  63.  
  64. }
  65.  
  66. int main() {
  67.  
  68.    int i;
  69.  
  70.    so_rt(0, 10);
  71.  
  72.    for(i = 0; i <11 ; i++){
  73.       cout << a[i] << " ";
  74.    }
  75.    cout << endl;
  76.  
  77.    return 0;
  78. }
  79.  
  80.  
  81.  
  82. //#########################Quick Sort : ######################
  83. #include <bits/stdc++.h>
  84. using namespace std;
  85.  
  86. int a[11] = { 10, 14, 19, 26, 27, 31, 33, 35, 42, 44, 0 };
  87.  
  88.     int parti_tion(int low , int high){
  89.     int pivot = a[high];
  90.     int i=low-1;
  91.  
  92.     for(int j=low ; j<high; j++){
  93.         if(a[j] < pivot){
  94.             i++;
  95.             int temp = a[i];
  96.             a[i] = a[j];
  97.             a[j] = temp;
  98.         }
  99.     }
  100.  
  101.     int temp = a[i+1];
  102.     a[i+1] = a[high];
  103.     a[high] = temp;
  104.  
  105.     return (i+1);
  106. }
  107.  
  108. void quick_sort( int low , int high){
  109.     if(low < high){
  110.  
  111.     int p = parti_tion(low , high);
  112.     quick_sort(low , p-1);
  113.     quick_sort(p+1 , high);
  114.  
  115.     }
  116.  
  117. }
  118.  
  119.  
  120. int main() {
  121.  
  122.    int i;
  123.  
  124.    quick_sort(0, 10);
  125.  
  126.    for(i = 0; i <11 ; i++){
  127.       cout << a[i] << " ";
  128.    }
  129.    cout << endl;
  130.  
  131.    return 0;
  132. }
  133.  
  134.  
  135.  
Add Comment
Please, Sign In to add comment