Exercise 1: Write a C program to implement Quick sort to sort an array of intege
ID: 3547080 • Letter: E
Question
Exercise 1: Write a C program to implement Quick sort to sort an array of integers.
step1: take first a list of unsorted values
step2: take first element as 'pivot'
step3: keep the first element as 'pivot' and correct its position in the list
step4: divide the list into two based on first element
step5: recursively sort the two sub-lists.
Sample output:
Array before sorting:
5 3 1 9 8 2 4 7
5 3 1 4 8 2 9 7
5 3 1 4 2 8 9 7
2 3 1 4 5 8 9 7
2 1 3 4
1 2 3 4
1 2 3 4
1 2 3 4 5 8 7 9
1 2 3 4 5 7 8 9
Array after sorting:
1 2 3 4 5 7 8 9 Press any key to continue
Write a C program to implement Quick sort to sort an array of integers.Explanation / Answer
here's the program
#include<stdio.h>
#include<conio.h>
void quicksort(int [10],int,int);
int main(){
int x[20],size,i;
printf("Quick Sort Program in C ");
printf("Enter size of the array: ");
scanf("%d",&size);
printf(" Enter %d values: ",size);
for(i=0;i<size;i++)
scanf("%d",&x[i]);
quicksort(x,0,size-1);
printf(" Sorted values: ");
for(i=0;i<size;i++)
printf(" %d",x[i]);
getch();
return 0;
}
void quicksort(int x[10],int first,int last){
int pivot,j,temp,i;
if(first<last){
pivot=first;
i=first;
j=last;
while(i<j){
while(x[i]<=x[pivot]&&i<last) i++; while(x[j]>x[pivot])
j--;
if(i<j){
temp=x[i];
x[i]=x[j];
x[j]=temp;
}
}
temp=x[pivot];
x[pivot]=x[j];
x[j]=temp;
quicksort(x,first,j-1);
quicksort(x,j+1,last);
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.