Advertisement
loulett

HW2_qsort_optimize

Dec 24th, 2014
171
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.74 KB | None | 0 0
  1. #include <cstdio>
  2. #include <cstdlib>
  3. #include <ctime>
  4.  
  5. int * generate(int* n)
  6. {
  7.     int * arr = (int *)malloc((*n) * sizeof(int));
  8.     for (int i = 0; i < *n; ++i)
  9.     {
  10.         arr[i] = rand();
  11.     }
  12.     return arr;
  13. }
  14.  
  15. void swap(int &a, int &b)
  16. {
  17.     int t = a;
  18.     a = b;
  19.     b = t;
  20. }
  21.  
  22. void inseption_sort(int* a, int n)
  23. {
  24.     int x, j;
  25.     for (int i = 0; i < n; i++)
  26.     {
  27.         x = a[i];
  28.         for (j = i - 1; j >= 0 && a[j] > x; j--)
  29.             a[j + 1] = a[j];
  30.         a[j + 1] = x;
  31.     }
  32. }
  33.  
  34.  
  35. int partition(int* a, int r)
  36. {
  37.     int i = 0;
  38.  
  39.     swap(a[rand() % r], a[r - 1]);
  40.  
  41.     for (int j = 0; j < r - 1; ++j)
  42.     {
  43.         if (a[j] < a[r - 1] || (a[j] == a[r - 1] && rand() & 1))
  44.         {
  45.             swap(a[i], a[j]);
  46.             i++;
  47.         }
  48.     }
  49.  
  50.     swap(a[i], a[r - 1]);
  51.  
  52.     return i;
  53. }
  54.  
  55. void quick_sort(int* a, int N)
  56. {
  57.     while (N > 1)
  58.     {
  59.         if (N < 40)
  60.         {
  61.             inseption_sort(a, N);
  62.             break;
  63.         }
  64.         int pivot = partition(a, N);
  65.         if (N - pivot > pivot)
  66.         {
  67.             quick_sort(a, pivot);
  68.             a += pivot;
  69.             N -= pivot;
  70.         }
  71.         else
  72.         {
  73.             quick_sort(a + pivot + 1, N - pivot - 1);
  74.             N = pivot;
  75.         }
  76.     }
  77. }
  78. int main()
  79. {
  80.     srand(time(NULL));
  81.     int n = 0, t = 0;
  82.     scanf("%i", &n);
  83.     int* arr = generate(&n);
  84.  
  85.     if (n > 100)
  86.         quick_sort(arr, n);
  87.     else
  88.         inseption_sort(arr, n);
  89.  
  90.     for (int i = 1; i < n; i++)
  91.     {
  92.         if (arr[i - 1] > arr[i])
  93.         {
  94.             printf("ERROR %d %d\n", arr[i - 1], arr[i]);
  95.             t++;
  96.         }
  97.     }
  98.     if (!t)
  99.     {
  100.         printf("OK\n");
  101.     }
  102.     return 0;
  103. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement