Advertisement
filashkov

QuickSort Hoare

Nov 24th, 2019
269
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.04 KB | None | 0 0
  1. //#include <iostream>
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <time.h>
  5.  
  6. //using namespace std;
  7.  
  8. void swap_f(int* a, int* b)
  9. {
  10.     *a = *a + *b;
  11.     *b = *a - *b;
  12.     *a = *a - *b;
  13. }
  14.  
  15. int partition(int* a, int left, int right)
  16. {
  17.     int pivot = left + rand() % (right - left);
  18.     pivot = a[pivot];
  19.     while (left <= right)
  20.     {
  21.         while (a[left] < pivot)
  22.         {
  23.             left++;
  24.         }
  25.         while (a[right] > pivot)
  26.         {
  27.             right--;
  28.         }
  29.         if (left >= right)
  30.         {
  31.             break;
  32.         }
  33.         swap_f(&a[left++], &a[right--]);
  34.     }
  35.     return right;
  36. }
  37.  
  38. void quickSort(int* a, int left, int right)
  39. {
  40.     if (left < right)
  41.     {
  42.         int pivot = partition(a, left, right);
  43.         quickSort(a, left, pivot);
  44.         quickSort(a, pivot + 1, right);
  45.     }
  46. }
  47.  
  48. int* Partition(int* left, int* right)
  49. {
  50.     int* pivot = left + rand() % (right - left);
  51.     while (left <= right)
  52.     {
  53.         while (*left < *pivot)
  54.         {
  55.             left++;
  56.         }
  57.         while (*right > *pivot)
  58.         {
  59.             right--;
  60.         }
  61.         if (left >= right)
  62.         {
  63.             break;
  64.         }
  65.         swap_f(left++, right--);
  66.     }
  67.     return right;
  68. }
  69.  
  70. void QuickSort(int* left, int* right)
  71. {
  72.     if (left < right)
  73.     {
  74.         int* pivot = Partition(left, right);
  75.         QuickSort(left, pivot);
  76.         QuickSort(pivot + 1, right);
  77.     }
  78. }
  79.  
  80. int main(void)
  81. {
  82.     //freopen("input.txt", "r", stdin);
  83.     //freopen("output.txt", "w", stdout);
  84.     srand(time(0));
  85.     int current_index = 0;
  86.     int* a = (int *)malloc(sizeof(int) * 100100);
  87.     int temp;
  88.     while (scanf("%d", &temp))
  89.     {
  90.         a[current_index++] = temp;
  91.     }
  92.     //quickSort(a, 0, current_index - 1);
  93.     QuickSort(a, a + current_index - 1);
  94.     for (int i = 0; i < current_index; i++)
  95.     {
  96.         printf("%d ", a[i]);
  97.     }
  98.     printf("\n");
  99.     return 0;
  100. }
  101.  
  102. /* 2 3 4 32 34 3456 54  567 654 32 34 54 32 3 4567 8 765 432 345 678 7 6543 2 567 ^D */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement