Write a c program for quick sort ?
#include<stdio.h>
void quicksort(int [30],int,int);
int main()
{
int array[40],size,i;
printf("Enter size of the array: ");
scanf("%d",&size);
printf("Enter %d elements: ",size);
for(i=0;i<size;i++)
scanf("%d",&array[i]);
quicksort(x,0,size-1);
printf("Sorted elements: ");
for(i=0;i<size;i++)
printf(" %d",array[i]);
return 0;
}
void quicksort(int array[30],int first,int last)
{
int pivot,j,temp,i;
if(first<last)
{
pivot=first;
i=first;
j=last;
while(i<j)
{
while(array[i]<=array[pivot]&&i<last)
i++;
while(array[j]>array[pivot])
j--;
if(i<j)
{
temp=array[i];
array[i]=array[j];
array[j]=temp;
}
}
temp=array[pivot];
array[pivot]=array[j];
array[j]=temp;
quicksort(array,first,j-1);
quicksort(array,j+1,last);
}
}
Output:
Enter size of the array: 5
Enter 5 elements: 3 8 0 1 2
Sorted elements: 0 1 2 3 8
#include<stdio.h>
void quicksort(int [30],int,int);
int main()
{
int array[40],size,i;
printf("Enter size of the array: ");
scanf("%d",&size);
printf("Enter %d elements: ",size);
for(i=0;i<size;i++)
scanf("%d",&array[i]);
quicksort(x,0,size-1);
printf("Sorted elements: ");
for(i=0;i<size;i++)
printf(" %d",array[i]);
return 0;
}
void quicksort(int array[30],int first,int last)
{
int pivot,j,temp,i;
if(first<last)
{
pivot=first;
i=first;
j=last;
while(i<j)
{
while(array[i]<=array[pivot]&&i<last)
i++;
while(array[j]>array[pivot])
j--;
if(i<j)
{
temp=array[i];
array[i]=array[j];
array[j]=temp;
}
}
temp=array[pivot];
array[pivot]=array[j];
array[j]=temp;
quicksort(array,first,j-1);
quicksort(array,j+1,last);
}
}
Output:
Enter size of the array: 5
Enter 5 elements: 3 8 0 1 2
Sorted elements: 0 1 2 3 8
very good
ReplyDelete