C program for quick sort algorithm

C program for quick sort algorithm

407
1
SHARE

C program for Quick Sort Algorithm : Quick sort is a divide and conquer algorithm. Quick sort first divides a large list into two smaller sub-lists: the low elements and the high elements. Quick sort can then recursively sort the sub-lists.

Let us see how quick sort algorithm works :

  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 sort the sub-list of lesser elements and the sub-list of greater elements.

The base case of the recursion are lists of size zero or one, which never need to be sorted.

Now lets see how this can be implemented using a .

C program for Quick Sort Algorithm :

#include<stdio.h>
#include<conio.h>
#include<math.h>
#include<time.h>
#include<stdlib.h>

void quicksort(int arr[], int low, int high);

int main() {
 int array[50] = {0};
 int i = 0,MAXARRAY;

 printf("\nEnter the number of elements :");
 scanf("%d",&MAXARRAY);
 printf("\nEnter the elements to be sorted : \n");
 for(i = 0; i < MAXARRAY; i++)
 {
       scanf("%d",&array[i]);

       }

 /* print the original array */
 printf("\nBefore quicksort:\n ");
 for(i = 0; i < MAXARRAY; i++) {
  printf(" %d ", array[i]);
 }
 printf("\n");

 quicksort(array, 0, (MAXARRAY - 1));

 /* print the `quicksorted' array */
 printf("\nAfter  quicksort:\n ");
 for(i = 0; i < MAXARRAY; i++) {
  printf(" %d ", array[i]);
 }
 printf("\n");
 printf("\n\n******************************************************");
 printf("\n*********** Code written by Ccodechamp ***************");
 printf("\n******************************************************");
 getch();
 return 0;
}

/* sort everything inbetween `low' <-> `high' */
void quicksort(int arr[], int low, int high) {
 int i = low;
 int j = high;
 int y = 0;
 /* compare value */
 int z = arr[(low + high) / 2];

 /* partition */
 do {
  /* find member above ... */
  while(arr[i] < z) i++;

  /* find element below ... */
  while(arr[j] > z) j--;

if(i <= j) {
   /* swap two elements */
   y = arr[i];
   arr[i] = arr[j];
   arr[j] = y;
   i++;
   j--;
  }
 } while(i <= j);

 /* recurse */
 if(low < j)
  quicksort(arr, low, j);

 if(i < high)
  quicksort(arr, i, high);
}

 

We hope that you all have enjoyed the in C. If you have any queries or doubts regarding the code, ask us in form of comments.

1 COMMENT

LEAVE A REPLY