forked from dimpeshmalviya/C-Language-Programs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQuickSortAlgorithm.c
More file actions
63 lines (49 loc) · 1.33 KB
/
QuickSortAlgorithm.c
File metadata and controls
63 lines (49 loc) · 1.33 KB
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
61
62
63
// C program to implement Quick Sort Algorithm
#include <stdio.h>
void swap(int* a, int* b) {
int temp = *a;
*a = *b;
*b = temp;
}
int partition(int arr[], int low, int high) {
// Initialize pivot to be the first element
int p = arr[low];
int i = low;
int j = high;
while (i < j) {
// Find the first element greater than
// the pivot (from starting)
while (arr[i] <= p && i <= high - 1) {
i++;
}
// Find the first element smaller than
// the pivot (from last)
while (arr[j] > p && j >= low + 1) {
j--;
}
if (i < j) {
swap(&arr[i], &arr[j]);
}
}
swap(&arr[low], &arr[j]);
return j;
}
void quickSort(int arr[], int low, int high) {
if (low < high) {
// call partition function to find Partition Index
int pi = partition(arr, low, high);
// Recursively call quickSort() for left and right
// half based on Partition Index
quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}
}
int main() {
int arr[] = { 4, 2, 5, 3, 1 };
int n = sizeof(arr) / sizeof(arr[0]);
// calling quickSort() to sort the given array
quickSort(arr, 0, n - 1);
for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
return 0;
}