Advertisement
cd62131

Quick Sort

Feb 1st, 2014
466
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.05 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <time.h>
  4. void quick(int *, int, int);
  5. int compare = 0, swap = 0;
  6. int main(void) {
  7.   srand((unsigned int) time(NULL));
  8.   printf("Number of trials: ");
  9.   int n;
  10.   scanf("%d", &n);
  11.   int r[n];
  12.   for (int i = 0; i < n; i++) {
  13.     r[i] = rand() % 100;
  14.   }
  15.   for (int i = 0; i < n; i++) printf("%d ", r[i]);
  16.   puts("");
  17.   quick(r, 0, n - 1);
  18.   puts("<クイックソート法>");
  19.   printf("比較回数: %d回\n", compare);
  20.   printf("交換回数: %d回\n", swap);
  21.   for (int i = 0; i < n; i++) printf("%d ", r[i]);
  22.   puts("");
  23.   return 0;
  24. }
  25.  
  26. void quick(int *a, int left, int right) {
  27.   int i = left;
  28.   int j = right;
  29.   int pivot = a[rand() % (j - i) + i];
  30.   while (1) {
  31.     while (a[i] < pivot) {
  32.       i++;
  33.       compare++;
  34.     }
  35.     while (a[j] > pivot) {
  36.       j--;
  37.       compare++;
  38.     }
  39.     if (i >= j) break;
  40.     int t = a[i];
  41.     a[i] = a[j];
  42.     a[j] = t;
  43.     swap++;
  44.     i++;
  45.     j--;
  46.   }
  47.   if (left < i - 1) quick(a, left, i - 1);
  48.   if (right > j + 1) quick(a, j + 1, right);
  49. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement