-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram_66.c
More file actions
58 lines (49 loc) · 1.46 KB
/
Copy pathProgram_66.c
File metadata and controls
58 lines (49 loc) · 1.46 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
// Program 66: Write a program to sort an array using Quick Sort.
/*
Quick Sort is a divide-and-conquer sorting algorithm.
It works by selecting a pivot element, placing the pivot at its correct position in the sorted array, and arranging all elements smaller than the pivot to its left and greater than the pivot to its right.
This process is then recursively applied to the left and right sub-arrays until the entire array is sorted.
*/
#include <stdio.h>
// Function to swap two elements
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
// Partition function
int partition(int arr[], int low, int high) {
int pivot = arr[high]; // choosing last element as pivot
int i = low - 1;
for(int j = low; j < high; j++) {
if(arr[j] < pivot) {
i++;
swap(&arr[i], &arr[j]);
}
}
swap(&arr[i + 1], &arr[high]);
return i + 1;
}
// Quick Sort function
void quickSort(int arr[], int low, int high) {
if(low < high) {
int pi = partition(arr, low, high);
quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}
}
// Main function
int main() {
int n;
printf("Enter number of elements: ");
scanf("%d", &n);
int arr[n];
printf("Enter elements:\n");
for(int i = 0; i < n; i++)
scanf("%d", &arr[i]);
quickSort(arr, 0, n - 1);
printf("Sorted array:\n");
for(int i = 0; i < n; i++)
printf("%d ", arr[i]);
return 0;
}