irongit

Dolphin type neovim.

neovim/samples/quicksort.c
71 lines1.3 KBC
1// quicksort
2
3#include <stdio.h>
4#include <stdlib.h>
5#include <time.h>
6
7#define N 10
8
9void quicksort(int a[], int low, int high);
10int partition(int a[], int low, int high);
11
12int main() {
13 int a[N];
14 int i;
15
16 srand(time(NULL));
17 for (i = 0; i < N; i++) {
18 a[i] = rand() % 1000;
19 }
20 printf("Before sorting:\n");
21 for (i = 0; i < N; i++) {
22 printf("%d ", a[i]);
23 }
24 printf("\n");
25
26 quicksort(a, 0, N - 1);
27
28 printf("After sorting:\n");
29 for (i = 0; i < N; i++) {
30 printf("%d ", a[i]);
31 }
32 printf("\n");
33
34 return 0;
35}
36
37void quicksort(int a[], int low, int high) {
38 int pivot;
39
40 if (low < high) {
41 pivot = partition(a, low, high);
42 quicksort(a, low, pivot - 1);
43 quicksort(a, pivot + 1, high);
44 }
45}
46
47int partition(int a[], int low, int high) {
48 int left, right, pivot_item = a[low];
49
50 left = low;
51 right = high;
52
53 while (left < right) {
54 while (a[left] <= pivot_item) {
55 left++;
56 }
57 while (a[right] > pivot_item) {
58 right--;
59 }
60 if (left < right) {
61 int temp = a[left];
62 a[left] = a[right];
63 a[right] = temp;
64 }
65 }
66
67 a[low] = a[right];
68 a[right] = pivot_item;
69
70 return right;
71}