C program to sort a random array of n integers (create a random array of n integers) in ascending order by using recursive Quick sort algorithm.

Quicksort algorithm :

Sort a random array of n integers (create a random array of n integers) in ascending order by using recursive Quick sort 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 :

How many elements are u going to enter?: 6
41 67 34 0 69 24
Order of Sorted elements:  0 24 34 41 67 69
Process returned 0 (0x0)   execution time : 1.970 s
Press any key to continue.

Post a Comment

0 Comments