Quick Sort algorithm to select random/middle/first/last element as a pivot

Below i have attached quick sort algorithm that can select pivot element position from the user for the first time and sort the array with  nlogn complexity.
Approx. in all the books ,algorithm shows to select  either first or last element as a pivot.This algorithm is able to select pivot position from user and sort the array elements accordingly.
Lets take an example:
95 5 1 3 7
try a quick sort dry run of this array elements on pen and paper,here 1 is a pivot element:-
1st pass:-1 5 95 3 7   (pivot element 1 is in final position)
2nd pass:-1 3 5 95 7  (now pivot element 5 is in final position)
3rd pass:-1 3 5 7 95   (pivot element 95 is in final position)

Just with the slight modification in the main & quick sort function , you can able to select middle element as a pivot element.To make a middle element as a pivot element,you only need to do three changes :
1.)Remove below two lines in the main function
   printf("Enter pivot element position===>\n");
2.) Add below lines in quicksort function
3.)Remove pivotpos paramter from quicksort and partition function.

You can also change your algorithm  to select first or last element as a pivot .You only need to do below changes in partition function and remove some code in quicksort function.
1.)pivotpos=left so that it always select first element in the list/sublist.
2.)pivotpos=right so that it always select last element in the list/sublist.

Here is the code that are able to select random pivot element from the user.I hope this code works for you as well, you can try run this code on  http://www.compileonline.com/compile_c_online.php.

If case you find anything  wrong or any type of suggestion,please comment below.
Happy Coding.

#include <stdio.h>
#include <string.h>
void quicksort(int arrElements[],int pivotpos,int start,int end){
    int newpivotpos=partition(arrElements,pivotpos,start,end);
int partition(int arrElements[],int pivotpos,int left,int right){
    int pivotValue=arrElements[pivotpos],checkPosFlag=0,start=left,end=right;
        while(arrElements[left]<=pivotValue && left<=end) left++;
        while(arrElements[right]>pivotValue) right--;

  return pivotpos;
int  swapElements(int *left,int *right){
    return 0;
    int arrayLength,i,pivotpos;
    printf("Enter Size of array=>\n");
   int arrElements[arrayLength];
   printf("Enter array Elements=>\n");
   printf("Enter pivot element position===>\n");
   printf("\nSorted Elements of array===>\n");


Popular posts from this blog

Getting started with Deep Learning Caffe Framework - Fastest way(Installation +Web Demo)

Sudoku using dancing link - Java implementation

OpenCV 2.4.9 JAVA/CPP/Python Installation in Ubuntu 14.04