c) Sort a random array of n integers (create a random array of n integers) in ascending order by using recursive Quick sort algorithm.
Solution:
int partition (int arr[], int low, int high)
{
int pivot = arr[high];
int i,j,t;
i= (low - 1);
for (j = low; j <= high- 1; j++)
{
if (arr[j] <= pivot)
{
i++;
t=arr[i];
arr[i]=arr[j];
arr[j]=t;
}
}
t=arr[i+1];
arr[i+1]=arr[high];
arr[high]=t;
return (i + 1);
}
void quickSort(int arr[], int low, int high)
{
int pi;
if (low < high)
{
pi = partition(arr, low, high);
quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}
}
void generate(int *a,int n)
{
int i;
for(i=0;i<n;i++)
a[i]=rand()%100;
}
void display(int *a,int n)
{
int i;
for(i=0;i<n;i++)
{
printf("%d\t",a[i]);
}
}
main()
{
int a[20],i,j,n;
printf("\n Enter how many elements:");
scanf("%d",&n);
generate(a,n);
printf("\n Elements are:\n");
display(a,n);
quickSort(a,0,n-1);
printf("\n After sorting elements are :\n");
display(a,n);
}
0 Comments:
Post a Comment