In: Computer Science
please write a C program that implements Quick Sort algorithm.
Quicksort is an algorithm for Divide and Conquer. The steps are as follows: 1) Pick an element from the array that is called as a pivot element. 2) Divide the unsorted array of elements into two arrays with values less than the pivot in the first sub-array, while the second sub-array contains all elements with values greater than the pivot. The partition operation is called this step. 3) Repeat step 2 (until the sub-arrays are sorted) recursively to the sub-array of elements with smaller values and to the sub-array of elements with larger values separately. The same logic that we implemented in the following C program.
C Program for Quicksort algorithm implementation.
#include<stdio.h>
void quicksort(int number[25],int first,int last){
int i, j, pivot, temp;
if(first<last){
pivot=first;
i=first;
j=last;
while(i<j){
while(number[i]<=number[pivot]&&i<last)
i++;
while(number[j]>number[pivot])
j--;
if(i<j){
temp=number[i];
number[i]=number[j];
number[j]=temp;
}
}
temp=number[pivot];
number[pivot]=number[j];
number[j]=temp;
quicksort(number,first,j-1);
quicksort(number,j+1,last);
}
}
int main(){
int i, count, number[25];
printf("How many elements are you going to enter?: ");
scanf("%d",&count);
printf("Enter %d elements: ", count);
for(i=0;i<count;i++)
scanf("%d",&number[i]);
quicksort(number,0,count-1);
printf("Sorted elements: ");
for(i=0;i<count;i++)
printf(" %d",number[i]);
return 0;
}
Output
