Register | Sing In

New posts

Stacks in C programming Linked Lists in C programming File Input/Output in C programming Check prime numbers in C Programming C Programming Enumeration C Programming Union

Archives

2013-10 2013-09 2013-08

Quick Sort in C Programming

August 25, 2013 Posted by: GPA Views: 567 0 comments

Problem

Quick Sort algorithm in C programming

Solution

Quick Sort algorithm is one of the fastest sorting algorithms. It average run time is O(n log n). Quick Sort is implemented using recursion. This article provides a demo of quick sort algorithm in C programming. 

Algorithm description:

This algorithm picks an element from array (preferably randomized mumber). Then compare the the values from left to right until a greater element is find then swap the values A similar operation is performed for the sets of data on the left to right recursively.

Example:

 

   

#include <stdio.h>
#include <stdlib.h>
void quicksort(int array[],int inputlow, int size);
int main(int argc, char *argv[])
{
     int A[10] = { 2, 6, 4, 8, 10, 12, 89, 68, 45, 37 };
     int size=10;//array size
     int i,j,k;//counter
     printf( "globalproganswer.com\n" );
    printf( "Array before Quick sorting:\n" );
     for ( i = 0; i < 10; i++ ) {
        printf( "%d ",A[i]);
     }
     quicksort(A,0,size-1);
     //show result after sorting
     printf("\n\nArray after Quick sorting:\n" );
   for ( i = 0; i < 10; i++ ) {
          printf( "%d ",A[i]);
    }
    printf("\n" );
   system("PAUSE");
    return 0;
}
//quicksort function
void quicksort(int array[],int inputlow, int size){
   int low = inputlow;
   int high = size;
   if (low >= size) {
       return;
   }
   int mid = array[(low + high) / 2];//devide array in 2 into left side and right side
   while (low < high) {//while 1
       while (low<high && array[low] < mid) {
       low++;
    }
    while (low<high && array[high] > mid) {
      high--;
    }
  if (low < high) {
       int temp = array[low];
       array[low] = array[high];
       array[high] = temp;
    }

  }//end while 1
if (high < low) {
int temp = high;
      high = low;
      low = temp;
   }
//call quicksort again
   quicksort(array, inputlow, low);
   quicksort(array, low == inputlow ? low+1 : low, size);
}

Output

Quick Sort in C example

Download this example

0 Comments...

Leave a Reply

Please, Sing In to leave a Reply for this material.



Online Chat

LiveZilla Live Help

Popular posts

Function strtok in C programming Check prime numbers in C Programming C Programming Union Linked Lists in C programming File Input/Output in C programming C Programming Enumeration

RSS-subscribe

New materials

Subscribe