Slip 7_1 : Sort a random array of n integers (accept the value of n from user) in ascending order by using quick sort algorithm.

 Solution :
#include<stdio.h>
void quicksort(int a[10],int lb,int ub);
main()
{ int n ,a[10],i,sr,j,temp;
 printf("\n enter no of elements");
 scanf("%d",&n);
 for(i=0;i<n;i++)
 {
 //printf("Enter no ");
 a[i]=rand()%100;
 }
 printf("\n Before sorted array is ");
 for(i=0;i<n;i++)
 {
 printf("%d ",a[i]);
 }
 quicksort(a,0,n-1);
 printf("\n Sorted array is ");
 for(i=0;i<n;i++)
 {
 printf("%d ",a[i]);
 }
}
void quicksort(int a[10],int lb,int ub)
{ int key,temp,i,j;
 if(lb<ub)
 {
 i=lb+1;
 key=a[lb];
 j=ub;
 while(i<=j)
 {
 while(a[i]<=key && i<=ub)
 i++;
 while(a[j]>key && j>=lb)
 j--;
 if(i<j)
{
 temp=a[i];
 a[i]=a[j];
 a[j]=temp;
 }
 }
 //swap key and a[j]
 temp=a[j];
 a[j]=a[lb];
 a[lb]=temp;
 quicksort(a,lb,j-1);
 quicksort(a,j+1,ub);
 }
}

Comments

Popular posts from this blog

Slip 22_2: Read the data from file 'cities.txt' containing names of cities and their STD codes. Accept a name of the city from user and use sentinel linear search algorithm to check whether the name is present in the file and output the STD code, otherwise output “city not in the list”. Solution :

Slip10_2, 30_1 : Read the data from the file “employee.txt” and sort on names in alphabetical order (use strcmp) using bubble sort or selection sort

Slip 23_2: Read the data from file ‘sortedcities.txt’ containing sorted names of cities and their STD codes. Accept a name of the city from user and use binary search algorithm to check whether the name is present in the file and output the STD code, otherwise output “city not in the list”.