Sort a random array of n integers (accept the value of n from user) in ascending order by using Quicksort algorithm.

Program :

 #include<stdio.h>

 #include<stdlib.h>



void quicksort(int a[25],int first,int last)

{

   int i, j, pivot, temp;



   if(first<last)

    {

      pivot=first;

      i=first;

      j=last;



      while(i<j)

        {

         while(a[i]<=a[pivot]&&i<last)

            i++;

         while(a[j]>a[pivot])

            j--;

         if(i<j){

            temp=a[i];

            a[i]=a[j];

            a[j]=temp;

         }

      }



      temp=a[pivot];

      a[pivot]=a[j];

      a[j]=temp;

      quicksort(a,first,j-1);

      quicksort(a,j+1,last);



   }

}



void generate(int a[],int n)

{

int i;

for(i=0;i<n;i++)

   a[i]=rand()%100;



}



int main(){

   int i, n, a[25];



   printf("How many elements are u going to enter?: ");

   scanf("%d",&n);

   generate(a,n);





   for(i=0;i<n;i++)

    printf("%d ",a[i]);



   quicksort(a,0,n-1);



   printf("\nOrder of Sorted elements: ");

   for(i=0;i<n;i++)

      printf(" %d",a[i]);



   return 0;

}

Output :

rohit@kali-linux:~$ cd Desktop/Ty
rohit@kali-linux:~/Desktop/Ty$ cc ok.c
rohit@kali-linux:~/Desktop/Ty$ ./a.out
How many elements are u going to enter?: 5
83 86 77 15 93 
Order of Sorted elements:
 15
 77
 83
 86
 93
rohit@kali-linux:~/Desktop/Ty$ 



Post a Comment

0 Comments