Quick Sort In C - Coders PlayGround

Learn to code and change the future!

Friday, 4 August 2017

Quick Sort In C

Hello guys, here is the program for Quick Sort in C


#include<stdio.h>
int n;
void display(int arr[],int n)
{
 int i ;
 printf("Elements of the array are :\n");
 for ( i = 0; i < n; ++i)
 {
  printf("%d ",arr[i]);
 }
 printf("\n\n");
}
int partition(int arr[],int p,int r)  //arr,p = 0,r = 3
{
 int x ,i,j,temp;
 x=arr[r+1];     // x = arr[4]
 i = p-1;     // i = -1
 for (j = p; j <= r; j++)  // j = 0,j<3,j++
 {
  if(arr[j]<=x)   
  {
   i++;
   temp = arr[j];
   arr[j] = arr[i];
   arr[i] = temp;
  }
 }
 i++;
 temp = arr[i];
 arr[i] = x;
 arr[j] = temp;
 return (i);
}
void quicksort(int arr[],int p,int r)  //arr,p=0,r=4
{
 if(p<r)
 {
  int q;
  q = partition(arr,p,r-1);  
  quicksort(arr,p,q-1);
  quicksort(arr,q+1,r);
 }
}

void main()
{
 int arr[10],i;
 printf("Enter the no of elements to be inserted : \n");
 scanf("%d",&n);   //n=5
 printf("Enter the values : \n");
 for(i=0;i<n;i++)
 {
  scanf("%d",&arr[i]);
 }
 printf("BEFORE SORTING\n");
 display(arr,n);   
 quicksort(arr,0,n-1);  //arr,0,4
 printf("AFTER SORTING\n");
 display(arr,n);
}
/*
Output : 

Enter the no of elements to be inserted : 
9
Enter the values : 
9
8
7
6
5
4
3
2
1
BEFORE SORTING
Elements of the array are :
9 8 7 6 5 4 3 2 1 

AFTER SORTING
Elements of the array are :
1 2 3 4 5 6 7 8 9 

lobo@lobo-Compaq-Presario-CQ60-Notebook-PC:~/Desktop$ 

*/

No comments:

PropellerAds