C++ Program to Implement Quick Sort

1. Introduction

Quick Sort is a divide-and-conquer sorting algorithm that works by selecting a 'pivot' element from the array and partitioning the other elements into two sub-arrays, depending on whether they are less than or greater than the pivot. The sub-arrays are then sorted recursively.

In this blog post, we will learn how to write a C++ program to implement Quick Sort.

2. Program Overview

The essential steps of the Quick Sort algorithm are:

1. Choose an element from the array as the pivot.

2. Partition the array around the pivot, such that elements smaller than the pivot come before it, while elements greater than the pivot come after.

3. Recursively apply the above steps to the sub-array of elements with smaller values and separately to the sub-array of elements with greater values.

3. Code Program

#include <iostream>
using namespace std;

// Utility function to swap two elements
void swap(int* a, int* b) {
    int temp = *a;
    *a = *b;
    *b = temp;
}

// This function takes last element as pivot, places the pivot element at its correct position, 
// and places all smaller to its left and all greater elements to its right
int partition(int arr[], int low, int high) {
    int pivot = arr[high];
    int i = (low - 1);

    for (int j = low; j <= high - 1; j++) {
        if (arr[j] < pivot) {
            i++;
            swap(&arr[i], &arr[j]);
        }
    }
    swap(&arr[i + 1], &arr[high]);
    return (i + 1);
}

void quickSort(int arr[], int low, int high) {
    if (low < high) {
        int pi = partition(arr, low, high);
        quickSort(arr, low, pi - 1);
        quickSort(arr, pi + 1, high);
    }
}

int main() {
    int arr[] = {10, 7, 8, 9, 1, 5};
    int n = sizeof(arr) / sizeof(arr[0]);
    quickSort(arr, 0, n-1);
    cout << "Sorted array: ";
    for (int i = 0; i < n; i++)
        cout << arr[i] << " ";
    cout << endl;
    return 0;
}

Output:

Sorted array: 1 5 7 8 9 10

4. Step By Step Explanation

The program begins by selecting a pivot element. In this code, the pivot is the last element of the array segment being considered. 

The partition function arranges the array in such a way that elements less than the pivot move to its left, and elements greater than it moves to its right. The position of the pivot after this arrangement is its sorted position. 

The quickSort function then recursively applies the same logic to the sub-arrays to the left and right of the pivot, thus breaking down the problem into smaller segments and sorting the entire array.

Comments