Sort a Given List of Numbers Using a Quick Sort - C Data Structure

C examples for Data Structure:Sort

Description

Sort a Given List of Numbers Using a Quick Sort

Demo Code

#include<stdio.h>

int myArray[20];// w  w  w  .  ja v a2 s  .c  om
int count = 10;

void swap(int n1, int n2)
{
   int temp = myArray[n1];
   myArray[n1] = myArray[n2];
   myArray[n2] = temp;
}

int partition(int left, int right, int pivot)
{
   int lPtr = left - 1;
   int rPtr = right;
   while (1) {
      while (myArray[++lPtr] < pivot) {
      }
      while (rPtr > 0 && myArray[--rPtr] > pivot) {
      }
      if (lPtr >= rPtr)
         break;
      else
         swap(lPtr, rPtr);
   }
   swap(lPtr, right);
   return lPtr;
}

void quickSort(int left, int right)
{
   int pivot, partPt;
   if (right - left <= 0) {
      return;
   }
   else {
      pivot = myArray[right];
      partPt = partition(left, right, pivot);
      quickSort(left, partPt - 1);
      quickSort(partPt + 1, right);
   }
}

void main()
{
   printf("Enter the 10 integers for quick sort separated by white spaces: \n");
   for (int i = 0; i < count; i++)
      scanf("%d", &myArray[i]);
   fflush(stdin);
   quickSort(0, count - 1);
   printf("Sorted List: ");
   for (int i = 0; i < count; i++)
      printf("%d ", myArray[i]);
   printf("\nThank you.\n");
}

Result


Related Tutorials