ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel
  • »
  • Technology»
  • Computers & Software»
  • Computer Science & Programming

Quick Sort C program for data structures

Updated on March 15, 2012

Introduction

In the quick sort method, an array a[1],..,a[n] is sorted by selecting some value in the array as a key element. We then swap the first element of the list with the key element so that the key will be in the first position. We then determine the key's proper place in the list. The proper place for the key is one in which all elements to the left of the key are smaller than the key, and all elements to the right are larger.

#include <stdio.h>
#define MAX 10
void swap(int *x,int *y)
{
   int temp;
   temp = *x;
   *x = *y;
   *y = temp;
}
int getkeyposition(int i,int j )
{
   return((i+j) /2);
}
void qsort(int list[],int m,int n)
{
   int key,i,j,k;
   if( m < n)
   {
      k = getkeyposition(m,n);
      swap(&list[m],&list[k]);
      key = list[m];
      i = m+1;
      j = n;
      while(i <= j)
      {
         while((i <= n) && (list[i] <= key))
                i++;
         while((j >= m) && (list[j] > key))
                j-;
         if( i < j)
                swap(&list[i],&list[j]);
      }
      swap(&list[m],&list[j]);
      qsort(list[],m,j-l);
      qsort(list[],j+1,n);
   }
}
void readlist(int list[],int n)
{
   int i;
   printf("Enter the elements\n");
   for(i=0;i<n;i++)
       scanf("%d",&list[i]);
}
void printlist(int list[],int n)
{
   int i;
   printf("The elements of the list are: \n");
   for(i=0;i<n;i++)
       printf("%d\t",list[i]);
}

void main()
{
   int list[MAX], n;
   printf("Enter the number of elements in the list max = 10\n");
   scanf("%d",&n);
   readlist(list,n);
   printf("The list before sorting is:\n");
   printlist(list,n);
   qsort(list,0,n-1);
   printf("\nThe list after sorting is:\n");
   printlist(list,n);
}

Comments

    0 of 8192 characters used
    Post Comment

    • profile image

      Satish 3 years ago

      http://www.comp-psyche.com/2014/06/quick-sort-prog...

      Here quick sort is explained with quick sort algorithm and program in c.

    • profile image

      Harshita Sinha 4 years ago

      this is nice..thanks

    • profile image

      Sara 5 years ago

      what's this hub for? we can get the program in the text books; better explain the code and compare against randomized version of quick sort, which would help.

    • profile image
      Author

      datastructuresinc 5 years ago

      Thanks. I hv added small introduction in beginning.

    • profile image

      Indigital 5 years ago

      You should give a brief explanation of what is does, for the noobs amongst us (me included).