Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <time.h>
- void quick(int *, int, int);
- int compare = 0, swap = 0;
- int main(void) {
- srand((unsigned int) time(NULL));
- printf("Number of trials: ");
- int n;
- scanf("%d", &n);
- int r[n];
- for (int i = 0; i < n; i++) {
- r[i] = rand() % 100;
- }
- for (int i = 0; i < n; i++) printf("%d ", r[i]);
- puts("");
- quick(r, 0, n - 1);
- puts("<クイックソート法>");
- printf("比較回数: %d回\n", compare);
- printf("交換回数: %d回\n", swap);
- for (int i = 0; i < n; i++) printf("%d ", r[i]);
- puts("");
- return 0;
- }
- void quick(int *a, int left, int right) {
- int i = left;
- int j = right;
- int pivot = a[rand() % (j - i) + i];
- while (1) {
- while (a[i] < pivot) {
- i++;
- compare++;
- }
- while (a[j] > pivot) {
- j--;
- compare++;
- }
- if (i >= j) break;
- int t = a[i];
- a[i] = a[j];
- a[j] = t;
- swap++;
- i++;
- j--;
- }
- if (left < i - 1) quick(a, left, i - 1);
- if (right > j + 1) quick(a, j + 1, right);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement