Question : Write a program to implent Quick Sort in C using Recursion.
Algorithm for swap() :
Step 1 : Start
Step 2 : int t;
Step 3 : t=*a;
Step 4 : *a=*b;
Step 5 : *b=t;
Step 6 : Stop.
Algorithm for partition() :
Step 1 : Start
Step 2 : int pivot=arr[high];
Step 3 : int i=low-1;
Step 4 : j=low; while (j<high), go to Step 5, else go to Step 9.
Step 5 : if (arr[j]<=pivot), go to Step 6, else go to Step 8.
Step 6 : i++;
Step 7 : swap(&arr[i],&arr[j]);
Step 8 : j++; Go to Step 4.
Step 9 : swap(&arr[i+1],&arr[high]);
Step 10 : return(i+1);
Step 11 : Stop.
Algorithm for quicksort() :
Step 1 : Start
Step 2 : if (low<high), go to Step 3, else go to Step 6.
Step 3 : int pi=partition(arr,low,high);
Step 4 : quicksort(arr,low,pi-1);
Step 5 : quicksort(arr,pi+1,high);
Step 6 : Stop.
Algorithm for printArray() :
Step 1 : Start
Step 2 : i=0;
Step 3 : while (i<10), go to Step 4, else go to Step 7.
Step 4 : printf(“%d”,arr[i]);
Step 5 : printf(“\n”);
Step 6 : i++. Go to Step 3.
Step 7 : Stop.
Algorithm for main() :
Step 1 : Start
Step 2 : int arr[10];
Step 3 : Display “Enter the array elements”.
Step 4 : i=0; while (i<10), go to Step 5, else go to Step 7.
Step 5 : scanf(“%d”,&arr[i]);
Step 6 : i++; Go to Step 4.
Step 7 : Display “The Array before sorting is \n”.
Step 8 : printArray(arr);
Step 9 : quicksort(arr,0,9);
Step 10 : Display “The Array after sorting is \n”.
Step 11 : printArray(arr);
Step 12 : Stop.
Program :
#include<stdio.h>
void swap(int *a,int *b)
{
int t;
t=*a;
*a=*b;
*b=t;
}
int partition(int arr[], int low, int high)
{
int pivot=arr[high];
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);
}
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);
}
}
void printArray(int arr[])
{
for(int i=0;i<10;i++)
printf("%d ",arr[i]);
printf("\n");
}
int main()
{
int i;
int arr[10];
printf("Enter the 10 elements of the array\n");
for(i=0;i<10;i++)
scanf("%d",&arr[i]);
printf("The array before sorting is :-\n");
printArray(arr);
quicksort(arr,0,9);
printf("The array after sorting is :-\n");
printArray(arr);
return 0;
}
Output :
Enter the 10 elements of the array
54
9
44
96
12
35
88
17
26
76
The array before sorting is :-
5494496123588172676
The array after sorting is :-
9121726354454768896
Remarks :
In this program we have learn how to implement the quick sort algorithm using
recursion. We have taken an array of 10 elements and have asked the user to input
the data according to their choice, next we have used the concept of quick sort in
order to sort the array in ascending order. Quick Sort is a relatively fast sorting
algorithm with its worse time being O(n2) and average time being O(nlogn).