Wednesday, October 30, 2013

c program to implement quicksort

9:36 AM


c program to implement quicksort

1. Quicksort is a divide and conquer algorithm.
2. Quicksort first divides a large list into two smaller sub-lists: the low elements and the high elements. Quicksort can then recursively sort the sub-lists.
The steps are:
  1. Pick an element, called a pivot, from the list.
  2. Reorder the list so that all elements with values less than the pivot come before the pivot, while all elements with values greater than the pivot come after it (equal values can go either way). After this partitioning, the pivot is in its final position. This is called the partition operation.
  3. Recursively apply the above steps to the sub-list of elements with smaller values and separately the sub-list of elements with greater values.

3.  on average,it makes O(n log n) comparisons to sort n items.


#include<stdio.h>
#include<conio.h>

int partition( int * , int , int  );
void quicksort( int *, int low, int high );
void display(int *, int);

void swap (int *a, int left, int right)
{
 int temp;
 temp=a[left];
 a[left]=a[right];
 a[right]=temp; 
}//end swap
void quicksort( int *a, int low, int high )
{
 int pivot;
 // Termination condition! 
 if ( high > low )
 {
  pivot = partition( a, low, high );
  quicksort( a, low, pivot-1 );
  quicksort( a, pivot+1, high );
 }
} //end quicksort
int partition( int *a, int low, int high )
{
 int left, right;
 int pivot_item;
 int pivot = left = low; 
 pivot_item = a[low]; 
 right = high;
 while ( left < right ) 
 {
  // Move left while item < pivot 
  while( a[left] <= pivot_item ) 
   left++;
  // Move right while item > pivot 
  while( a[right] > pivot_item ) 
   right--;
  if ( left < right ) 
   swap(a,left,right);
 }
 // right is final position for the pivot 
 a[low] = a[right];
 a[right] = pivot_item;
 return right;
}//end partition


int main()
{
 int a[50], i, n;
 printf("\nEnter no. of elements: "); 
 scanf("%d", &n);
 printf("\nEnter the elements: \n");
 for (i=0; i<n; i++)
  scanf ("%d", &a[i]);
 printf("\nUnsorted elements: \n");
 display(a,n);
 quicksort(a,0,n-1);
 printf("\nSorted elements: \n");
 display(a,n);
 getch();
 return 0;
}//end main
void display(int *a, int n)
{
 int i;
 for (i=0; i<n; i++)
  printf(" %d ", a[i]);
 printf("\n");
}//end display


Below is the output of the above program.





Written by

We are Creative Blogger Theme Wavers which provides user friendly, effective and easy to use themes. Each support has free and providing HD support screen casting.

0 comments:

Post a Comment

 

© 2013 1000TechTips. All rights resevered. Designed by Templateism

Back To Top