## Sorting algorithm : quicksort in C

Quicksort is a sorting algorithm with which we can sort a number of element in ascending or descending order. When we use quicksort then the algorithm works in following process.

Quicksort takes the first element as pivot element and divide the the whole array in two sub array. First sub array contains all the number less than the pivot element and second sub array contains all the numbers greater than that pivot element.

Again each sub array is divided into another two array taking first element as the pivot element. This process continues until we get the sorted array as we have given in the following figure.

Now, let’s see the program implementing this idea to sort an array of integer using quicksort in C.

## C program using quicksort algorithm

``````// C program using quicksort algorithm

#include<stdio.h>

void quicksort_funct(int array_of_num[50], int n1, int n2);

int main(){
int num_arr[50], num, c;

printf("Enter the number of elements here : ");
scanf("%d", &num);

printf("Enter total %d integers here : \n", num);

for(c = 0; c < num; c++){
scanf("%d", &num_arr[c]);
}

quicksort_funct(num_arr, 0, (num-1) );

printf("\nAfter sorting, elements are : \n");

for(c = 0; c < num; c++){
printf("%d ", num_arr[c]);
}

return 0;
}

// function for quicksort
void quicksort_funct(int array_of_num[50], int n1, int n2){
int pivot, t, a, b;

if(n1 < n2){
pivot = n1;
a = n1;
b = n2;

while(a < b){

while(array_of_num[a] <= array_of_num[pivot] && a < n2){
a++;
}

while(array_of_num[b] > array_of_num[pivot]){
b--;
}

if(a < b){
t = array_of_num[a];
array_of_num[a] = array_of_num[b];
array_of_num[b] = t;
}
}

t = array_of_num[pivot];
array_of_num[pivot] = array_of_num[b];
array_of_num[b] = t;
quicksort_funct(array_of_num, n1, b-1);
quicksort_funct(array_of_num, b+1, n2);

}
}``````

### Output of this quicksort program

``````Enter the number of elements here : 12
Enter total 12 integers here :
33 43 25 47 46 87 69 40 91 37 57 43

After sorting, elements are :
25 33 37 40 43 43 46 47 57 69 87 91``````

Previous page:Â  Selection sort

Next page:Â  Binary search

Recommended for you: