Data Structure and Algorithms - Quick Sort


Quick sort is a highly efficient sorting algorithm and is based on partitioning of array of data into smaller arrays. A large array is partitioned into two arrays one of which holds values smaller than the specified value, say pivot, based on which the partition is made and another array holds values greater than the pivot value.

Quicksort partitions an array and then calls itself recursively twice to sort the two resulting subarrays. This algorithm is quite efficient for large-sized data sets as its average and worst-case complexity are O(n2), respectively.

Partition in Quick Sort

Following animated representation explains how to find the pivot value in an array.

Quick Sort Partition Animation

The pivot value divides the list into two parts. And recursively, we find the pivot for each sub-lists until all lists contains only one element.

Quick Sort Pivot Algorithm

Based on our understanding of partitioning in quick sort, we will now try to write an algorithm for it, which is as follows.

Step 1 − Choose the highest index value has pivot
Step 2 − Take two variables to point left and right of the list excluding pivot
Step 3 − left points to the low index
Step 4 − right points to the high
Step 5 − while value at left is less than pivot move right
Step 6 − while value at right is greater than pivot move left
Step 7 − if both step 5 and step 6 does not match swap left and right
Step 8 − if left ≥ right, the point where they met is new pivot

Quick Sort Pivot Pseudocode

The pseudocode for the above algorithm can be derived as −

function partitionFunc(left, right, pivot)
   leftPointer = left
   rightPointer = right - 1

   while True do
      while A[++leftPointer] < pivot do
         //do-nothing            
      end while
		
      while rightPointer > 0 && A[--rightPointer] > pivot do
         //do-nothing         
      end while
		
      if leftPointer >= rightPointer
         break
      else                
         swap leftPointer,rightPointer
      end if
		
   end while 
	
   swap leftPointer,right
   return leftPointer
	
end function

Quick Sort Algorithm

Using pivot algorithm recursively, we end up with smaller possible partitions. Each partition is then processed for quick sort. We define recursive algorithm for quicksort as follows −

Step 1 − Make the right-most index value pivot
Step 2 − partition the array using pivot value
Step 3 − quicksort left partition recursively
Step 4 − quicksort right partition recursively

Quick Sort Pseudocode

To get more into it, let see the pseudocode for quick sort algorithm −

procedure quickSort(left, right)

   if right-left <= 0
      return
   else     
      pivot = A[right]
      partition = partitionFunc(left, right, pivot)
      quickSort(left,partition-1)
      quickSort(partition+1,right)    
   end if		
   
end procedure

Example

#include <stdio.h>
#include <stdbool.h>
#define MAX 7
int intArray[MAX] = {4,6,3,2,1,9,7};
void printline(int count) {
   int i;
   for(i = 0;i < count-1;i++) {
      printf("=");
   }
   printf("=\n");
}
void display() {
   int i;
   printf("[");
	
   // navigate through all items 
   for(i = 0;i < MAX;i++) {
      printf("%d ",intArray[i]);
   }
   printf("]\n");
}
void swap(int num1, int num2) {
   int temp = intArray[num1];
   intArray[num1] = intArray[num2];
   intArray[num2] = temp;
}
int partition(int left, int right, int pivot) {
   int leftPointer = left -1;
   int rightPointer = right;

   while(true) {
      while(intArray[++leftPointer] < pivot) {
         //do nothing
      }	
      while(rightPointer > 0 && intArray[--rightPointer] > pivot) {
         //do nothing
      }
      if(leftPointer >= rightPointer) {
         break;
      } else {
         printf(" item swapped :%d,%d\n", intArray[leftPointer],intArray[rightPointer]);
         swap(leftPointer,rightPointer);
      }
   }
   printf(" pivot swapped :%d,%d\n", intArray[leftPointer],intArray[right]);
   swap(leftPointer,right);
   printf("Updated Array: "); 
   display();
   return leftPointer;
}
void quickSort(int left, int right) {
   if(right-left <= 0) {
      return;   
   } else {
      int pivot = intArray[right];
      int partitionPoint = partition(left, right, pivot);
      quickSort(left,partitionPoint-1);
      quickSort(partitionPoint+1,right);
   }        
}
int main() {
   printf("Input Array: ");
   display();
   printline(50);
   quickSort(0,MAX-1);
   printf("Output Array: ");
   display();
   printline(50);
}

Output

Array elements before quick sort are: [4 6 3 2 1 9 7 ]
**************************************************
pivot swapped: 9, 7
Updated Array: [4 6 3 2 1 7 9 ]
pivot swapped: 4, 1
Updated Array: [1 6 3 2 4 7 9 ]
item swapped: 6, 2
pivot swapped: 6, 4
Updated Array: [1 2 3 4 6 7 9 ]
pivot swapped: 3, 3
Updated Array: [1 2 3 4 6 7 9 ]
Array elements after quick sort are: [1 2 3 4 6 7 9 ]
**************************************************
//C++ program for Quick Sort Algorithm
#include <iostream>
#include <stdbool.h>
#define MAX 7
int intArray[MAX] = {4,6,3,2,1,9,7};
void printline(int count) {
   int i;	
   for(i = 0;i < count-1;i++) {
      std::cout << "=";
   }
   std::cout << "=\n";
}
void display() {
   int i;
   std::cout << "[";
   // navigate through all items 
   for(i = 0;i < MAX;i++) {
      std::cout << intArray[i] << " ";
   }
   std::cout << "]\n";
}
void swap(int num1, int num2) {
   int temp = intArray[num1];
   intArray[num1] = intArray[num2];
   intArray[num2] = temp;
}
int partition(int left, int right, int pivot) {
   int leftPointer = left -1;
   int rightPointer = right;
   while(true) {
      while(intArray[++leftPointer] < pivot) {
         //do nothing
      }	
      while(rightPointer > 0 && intArray[--rightPointer] > pivot) {
         //do nothing
      }
      if(leftPointer >= rightPointer) {
         break;
      } else {
         std::cout << " item swapped :" << intArray[leftPointer] << "," << intArray[rightPointer] << "\n";
         swap(leftPointer,rightPointer);
      }
   }
   std::cout << " pivot swapped :" << intArray[leftPointer] << "," << intArray[right] << "\n";
   swap(leftPointer,right);
   std::cout << "Updated Array: "; 
   display();
   return leftPointer;
}
void quickSort(int left, int right) {
     if(right-left <= 0) {
      return;   
   } else {
      int pivot = intArray[right];
      int partitionPoint = partition(left, right, pivot);
      quickSort(left,partitionPoint-1);
      quickSort(partitionPoint+1,right);
   }        
}
int main() {
   std::cout << "Input Array: ";
   display();
   printline(50);
   quickSort(0, MAX-1);
   std::cout << "Output Array: ";
   display();
   printline(50);
   return 1;
}

Output

Input Array: [4 6 3 2 1 9 7 ]
==================================================
 pivot swapped :9,7
Updated Array: [4 6 3 2 1 7 9 ]
 pivot swapped :4,1
Updated Array: [1 6 3 2 4 7 9 ]
 item swapped :6,2
 pivot swapped :6,4
Updated Array: [1 2 3 4 6 7 9 ]
 pivot swapped :3,3
Updated Array: [1 2 3 4 6 7 9 ]
Output Array: [1 2 3 4 6 7 9 ]
==================================================
//Java program for Quick Sort Algorithm
class QuickSort {
    static int intArray[] = {4, 6, 3, 2, 1, 9, 7};
    int MAX;
    QuickSort(int MAX) {
        this.MAX = MAX;
    }
    public void printline(int count) {
        for (int i = 0; i < count - 1; i++) {
            System.out.print("*");
        }
        System.out.println("*");
    }
    public void display() {
        System.out.print("[");
        //navigate through all items
        for (int i = 0; i < this.MAX; i++) {
            System.out.print(intArray[i] + " ");
        }
        System.out.println("]");
    }
    public void swap(int num1, int num2) {
        int temp = intArray[num1];
        intArray[num1] = intArray[num2];
        intArray[num2] = temp;
    }
    public int partition(int left, int right, int pivot) {
        int leftPointer = left - 1;
        int rightPointer = right;
        while (true) {
            while (intArray[++leftPointer] > pivot) {
                // do nothing
            }
            while (rightPointer > 0 && intArray[--rightPointer] > pivot) {
                // do nothing
            }
            if (leftPointer >= rightPointer) {
                break;
            } else {
                System.out.println("item swapped: " + intArray[leftPointer] + ", " + intArray[rightPointer]);
                swap(leftPointer, rightPointer);
            }
        }
        System.out.println("pivot swapped: " + intArray[leftPointer] + ", " + intArray[right]);
        swap(leftPointer, right);
        System.out.print("Updated Array: ");
        display();
        return leftPointer;
    }
    public void quickSort(int left, int right) {
        if (right - left <= 0) {
            return;
        } else {
            int pivot = intArray[right];
            int partitionPoint = partition(left, right, pivot);
            quickSort(left, partitionPoint - 1);
            quickSort(partitionPoint + 1, right);
        }
    }
}
public class main {
    public static void main(String[] args) {
        int MAX = 7;
        //create an object of the QuickSort class
        QuickSort qs = new QuickSort(MAX);
        System.out.print("Array elements before quick sort are: ");
        qs.display();
        qs.printline(50);
        qs.quickSort(0, MAX - 1);
        System.out.print("Array elements after quick sort are: ");
        qs.display();
        qs.printline(50);
    }
}

Output

Array elements before quick sort are: [4 6 3 2 1 9 7 ]
**************************************************
pivot swapped: 9, 7
Updated Array: [4 6 3 2 1 7 9 ]
pivot swapped: 4, 1
Updated Array: [1 6 3 2 4 7 9 ]
item swapped: 6, 2
pivot swapped: 6, 4
Updated Array: [1 2 3 4 6 7 9 ]
pivot swapped: 3, 3
Updated Array: [1 2 3 4 6 7 9 ]
Array elements after quick sort are: [1 2 3 4 6 7 9 ]
**************************************************
#python program for Quick Sort Algorithm
intArray = [4, 6, 3, 2, 1, 9, 7]
MAX = 7
def printline(count):
    for i in range(count - 1):
        print("=", end="")
    print("=")
def display():
    print("[", end="")
    for i in range(MAX):
        print(intArray[i], end=" ")
    print("]")
def swap(num1, num2):
    temp = intArray[num1]
    intArray[num1] = intArray[num2]
    intArray[num2] = temp
def partition(left, right, pivot):
    leftPointer = left
    rightPointer = right - 1
    while True:
        while leftPointer <= right and intArray[leftPointer] < pivot:
            leftPointer += 1
        while rightPointer >= left and intArray[rightPointer] > pivot:
            rightPointer -= 1
        if leftPointer >= rightPointer:
            break
        else:
            print(" item swapped :", intArray[leftPointer], ",",
                  intArray[rightPointer])
            swap(leftPointer, rightPointer)
    print(" pivot swapped :", intArray[leftPointer], ",", intArray[right])
    swap(
        leftPointer, right
    )  # Swapping the pivot with the leftPointer (which is now at the correct position)
    print("Updated Array: ", end="")
    display()
    return leftPointer
def quickSort(left, right):
    if right <= left:
        return
    else:
        pivot = intArray[right]
        partitionPoint = partition(left, right, pivot)
        quickSort(left, partitionPoint - 1)
        quickSort(partitionPoint + 1, right)
intArray = [4, 6, 3, 2, 1, 9, 7]
MAX = 7
print("Input Array: ", end="")
display()
printline(50)
quickSort(0, MAX - 1)
print("Output Array: ", end="")
display()
printline(50)

Output

Array elements before quick sort are: [4 6 3 2 1 9 7 ]
**************************************************
pivot swapped: 9, 7
Updated Array: [4 6 3 2 1 7 9 ]
pivot swapped: 4, 1
Updated Array: [1 6 3 2 4 7 9 ]
item swapped: 6, 2
pivot swapped: 6, 4
Updated Array: [1 2 3 4 6 7 9 ]
pivot swapped: 3, 3
Updated Array: [1 2 3 4 6 7 9 ]
Array elements after quick sort are: [1 2 3 4 6 7 9 ]
**************************************************
Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements