The Program in C to sort the array using quick sort using recursion technique inputted by user is given below:
#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[high];
int i = low - 1;
for (int j = low; j <= high - 1; j++) {
if (arr[j] <= pivot) {
i++;
swap(&arr[i], &arr[j]);
}
}
swap(&arr[i + 1], &arr[high]);
return (i + 1);
}
void quick_sort(int arr[], int low, int high) {
if (low < high) {
int pi = partition(arr, low, high);
quick_sort(arr, low, pi - 1);
quick_sort(arr, pi + 1, high);
}
}
int main() {
int size;
printf("Enter the size of the array: ");
scanf("%d", &size);
int arr[size];
printf("Enter the elements of the array: ");
for (int i = 0; i < size; i++) {
scanf("%d", &arr[i]);
}
quick_sort(arr, 0, size - 1);
printf("The sorted array is: ");
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
return 0;
}
Output:
Enter the size of the array: 3
Enter the elements of the array: 12
56
78
The sorted array is: 12 56 78
Pro-Tips💡
This program defines a function quick_sort()
which takes in 3 parameters: the array arr
, the lower index low
and the upper index high
of the array which needs to be sorted.
The function uses recursion to sort the array using the Quick Sort algorithm. It first partition the array using the pivot element, then recursively sort the sub-arrays to the left and right of the pivot element.
The pivot point is selected as the last element of the array.
It also have a helper function called partition
which takes 3 parameters: the array arr
, the lower index low
and the upper index high
of the array which needs to be partitioned.
It divides the array into two parts, one with elements less than the pivot and one with elements greater than the pivot.
It uses two indices to traverse the array and swap the elements if the element is less than the pivot.
In the main function, the program prompts the user to enter the number of elements in the array and the array elements one by one.
Then it calls the quick_sort()
function with the array, and the lower and upper indices as arguments, which sorts the array.
The program then prints the sorted array.
Learn C-Sharp ↗
C-sharp covers every topic to learn about C-Sharp thoroughly.
Learn C Programming ↗
C-Programming covers every topic to learn about C-Sharp thoroughly.
Learn C++ Programming↗
C++ covers every topic to learn about C-Sharp thoroughly.