Ladies_Man

#SORT__Quick + Select (Быстрая - Выбором)

Dec 17th, 2013
158
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.69 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. int *array;
  5. int n;
  6.  
  7. void swap(int i, int j)
  8. {
  9.         int t = array[i];
  10.         array[i] = array[j];
  11.         array[j] = t;
  12. }
  13.  
  14. void selectsort (int low, int high, void (*swap)(int, int))
  15. {
  16.     int i = low, j = high, k;
  17.     while (j > low) {
  18.         k = j;
  19.         i = j - 1;
  20.         while (i >= 0) {
  21.             if (array[k] < array[i])
  22.                 k = i;
  23.             i--;
  24.         }
  25.         swap (j, k);
  26.         j--;
  27.     }
  28. }
  29.  
  30. void quicksortrec (int low, int high, int m, void (*swap)(int, int))
  31. {//(wiki)
  32.     if (high - low + 1 <= m) {
  33.         selectsort(low, high, swap);
  34.         return;
  35.     }
  36.  
  37.     while (low != high) {
  38.  
  39.         int i = low, j = high;
  40.         int mid = array[(low + high) / 2];
  41.  
  42.         while (i <= j) {
  43.  
  44.             while (array[i] < mid) i++;
  45.             while (array[j] > mid) j--;
  46.  
  47.             if (i <= j) {
  48.                 swap(i, j);
  49.                 i++;
  50.                 j--;
  51.             }
  52.  
  53.         }
  54.  
  55.         if ((j - low) < (high - i)) {
  56.             if (low < j) quicksortrec(low, j, m, swap);
  57.             low = i;
  58.         }
  59.         else {
  60.             if (i < high) quicksortrec(i, high, m, swap);
  61.             high = j;
  62.         }
  63.  
  64.     }
  65. }
  66.  
  67. void quicksort (int n, int m, void (*swap)(int, int))
  68. {
  69.     quicksortrec (0, n-1, m, swap);
  70. }
  71.  
  72. int main()
  73. {
  74.     int i, n, m;
  75.  
  76.     scanf("%d", &n);
  77.     scanf("%d", &m);
  78.  
  79.     array = (int*)malloc(n*sizeof(int));
  80.     for (i = 0; i < n; i++) scanf("%d", array+i);
  81.  
  82.     quicksort (n, m, swap);
  83.     //selectsort(0, n, swap);
  84.  
  85.     //printf("Result:\n");
  86.     for (i = 0; i < n; i++) printf("%d ", array[i]);
  87.  
  88.     free(array);
  89.     return 0;
  90. }
Advertisement
Add Comment
Please, Sign In to add comment