w3resource logo


C Programming Exercises

C Exercises: Quick sort algorithm

Secondary Nav

C Programming Searching and Sorting Algorithm: Exercise-7 with Solution

Write a C program to sort a list of elements using the quick sort algorithm.

Note: Quick sort is a comparison sort, meaning that it can sort items of any type for which a "less-than" relation (formally, a total order) is defined.
Read n values into array and Sort using Quick Sort.

Pictorial presentation - Quick Sort algorithm :

C programming Quick sort algorithm part-1

C programming Quick sort algorithm part-2

Sample C Code:

#include<stdio.h>
  int  n;
  void  main()
  {
  int arr[30],l,r,i;
  void quick_sort(int arr[],int,int);
  printf("\nInput number of elements:  ");
  scanf(" %d",&n);
  printf("\nInput  array values one by one: ");
  for(i=0;i<n;i++)
  scanf(" %d",&arr[i]);
  l=0; r=n-1;
  quick_sort(arr,l,r);
  printf("\nThe quick sorted array is:  ");
  for(i=0;i<n;i++)
  printf(" %d",arr[i]);
  printf("\n");
  }
  void quick_sort(int arr[],int low,int high)
  {
  int temp,left,right,x,k;
  if(low>=high)
  return;
  else
  {
  x=arr[low];
  right=low+1;
  left = high;
  while(right<=left)
  {
  while(arr[right]<x && right  <= high)
  {
  right ++;
  }
  while(arr[left]>x && left >  low)
  {
  left--;
  }
  if(right<left)
  {
  temp=arr[right];
  arr[right]=arr[left];
  arr[left]=temp;
  right++;
  left--;
  }
  }
  arr[low]=arr[left];
  arr[left]=x;
  quick_sort(arr,low,left-1);
  quick_sort(arr,left+1,high);
  }
  }

Flowchart :

Flowchart: C Programming - Quick sort

C Code Editor:

#include<stdio.h>
  int  n;
  void  main()
  {
  int arr[30],l,r,i;
  void quick_sort(int arr[],int,int);
  printf("\nInput number of elements:  ");
  scanf(" %d",&n);
  printf("\nInput  array values one by one: ");
  for(i=0;i<n;i++)
  scanf(" %d",&arr[i]);
  l=0; r=n-1;
  quick_sort(arr,l,r);
  printf("\nThe quick sorted array is:  ");
  for(i=0;i<n;i++)
  printf(" %d",arr[i]);
  printf("\n");
  }
  
  void quick_sort(int arr[],int low,int high)
  {
  int temp,left,right,x,k;
  if(low>=high)
  return;
  else
  {
  x=arr[low];
  right=low+1;
  left = high;
  while(right<=left)
  {
  while(arr[right]<x && right  <= high)
  {
  right ++;
  }
  while(arr[left]>x && left >  low)
  {
  left--;
  }
  if(right<left)
  {
  temp=arr[right];
  arr[right]=arr[left];
  arr[left]=temp;
  right++;
  left--;
  }
  }
  arr[low]=arr[left];
  arr[left]=x;
  quick_sort(arr,low,left-1);
  quick_sort(arr,left+1,high);
  }
  }

Improve this sample solution and post your code through Disqus.



Join our Question Answer community to learn and share your programming knowledge.

Solve these problems:

Java: How to convert a string to an integer in Java?

C#: Loops in c#

SQL: JOIN using more than 5 tables