-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathquicksort.c
60 lines (50 loc) · 1.07 KB
/
quicksort.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#include <stdio.h>
void swap(int *a, int *b)
{
int temp = *a;
*a = *b;
*b = temp;
}
int partition(int arr[], int low, int high)
{
int pivot = arr[low];
int start = low;
int end = high;
while(start < end)
{
while(arr[start] <= pivot)
start++;
while(arr[end] > pivot)
end--;
if(start <= end)
swap(&arr[start], &arr[end]);
}
swap(&arr[low], &arr[end]);
return end;
}
void quicksort(int arr[], int low, int high)
{
int pivotIndex;
if (low < high)
{
pivotIndex = partition(arr, low, high);
quicksort(arr, low, pivotIndex - 1);
quicksort(arr, pivotIndex + 1, high);
}
}
int main()
{
int n, i;
int arr[n];
printf("Enter the number of elements in the array: ");
scanf("%d", &n);
printf("Enter the elements of the array:\n");
for (i = 0; i < n; i++)
scanf("%d", &arr[i]);
quicksort(arr, 0, n - 1);
printf("Sorted array: ");
for (i = 0; i < n; i++)
printf("%d ", arr[i]);
printf("\n");
return 0;
}