×

Quick Sort in C++

Quick sort is an efficient, in-place, comparison-based sorting algorithm that uses a divide-and-conquer strategy to sort an array or list of elements. First a pivot element is selected from the array and it partitions the other elements into two sub-arrays, doesn’t whether they are less or greater than the pivot. The pivot element is then in its final position in the sorted array. The sub-arrays are then recursively sorted using the same algorithm.

Following steps are used for quick sort:

  1. Define a partition function that takes three arguments: the array, the low index, and the high index.
  2. Within the partition function, choose the pivot element as the last element of the array.
  3. Using two pointers, i and j, in order to iterate through the array.
  4. If the current element is less than or equal to the pivot, swap it with the element at the pointer i and increment both i and j.
  5. When the iteration is complete, swap the pivot element with the element at the pointer i+1. This places the pivot element in its final position in the sorted array.
  6. Return the pivot index i+1.
  7. Define a quickSort function that takes three arguments: the array, the low index, and the high index.
  8. Inside the quickSort function, check if the low index is lesser than the high index.
  9. If the low index is less than the high index, call the partition function to get the pivot index.
  10. Recursively call the quickSort function for the sub-array to the left of the pivot index and the sub-array to the right of the pivot index.
  11. Repeat steps 8-10 until the sub-array has only one element.
  12. The array is now sorted.

In the main function, create an array of integers and call the quickSort function to sort the array. Finally, print the sorted array.

Here is an example of Quick Sort implemented in C++:

Example:

// C++ Implementation of the Quick Sort Algorithm.
#include <iostream>
using namespace std;
int partition(int arr[], int start, int end)
{


	int pivot = arr[start];


	int count = 0;
	for (int i = start + 1; i <= end; i++) {
		if (arr[i] <= pivot)
			count++;
	}


	// Giving pivot element its correct position
	int pivotIndex = start + count;
	swap(arr[pivotIndex], arr[start]);


	// Sorting left and right parts of the pivot element
	int i = start, j = end;


	while (i < pivotIndex && j > pivotIndex) {


		while (arr[i] <= pivot) {
			i++;
		}


		while (arr[j] > pivot) {
			j--;
		}


		if (i < pivotIndex && j > pivotIndex) {
			swap(arr[i++], arr[j--]);
		}
	}


	return pivotIndex;
}


void quickSort(int arr[], int start, int end)
{


	// base case
	if (start >= end)
		return;


	// partitioning the array
	int p = partition(arr, start, end);


	// Sorting the left part
	quickSort(arr, start, p - 1);


	// Sorting the right part
	quickSort(arr, p + 1, end);
}


int main()
{


	int arr[] = { 90, 32, 46, 21, 18, 88 };
	int n = 6;


	quickSort(arr, 0, n - 1);


	for (int i = 0; i < n; i++) {
		cout << arr[i] << " ";
	}


	return 0;
}

Output:

18 21 32 46 88 90

Now, you can see that input array [90, 32, 46, 21, 18, 88] is sorted now to 18 21 32 46 88 90.

Program Explanation:

The function partition() is used to find the pivot element and partition the array around it. The quickSort() function is then used to recursively sort the sub-arrays on either side of the pivot. In this example, the pivot element is the last element of the array.

In the example of Quick Sort in C++ provided above, the function partition() is used to find the pivot element and partition the array around it. It takes three arguments: the array, the start index, and the end index. The pivot element is chosen as the last element of the array. The function uses two pointers, i and j, to iterate through the array. If the current element is less than or equal to the pivot, it is swapped with the element at the pointer i and both i and j are incremented. This way, elements less than pivot are moved towards the left and element greater than pivot towards the right.

The quickSort() function is then used to recursively sort the sub-arrays on either side of the pivot. The partition index (pi) is obtained by calling the partition function. The function then recursively calls itself for the sub-array to the left of the partition index and the sub-array to the right of the partition index. It does this until the low index is less than the high index.

In the main function, it creates an array of integers and calls the quickSort() function to sort the array. It then prints the sorted array.

Conclusion:

Overall, Quick Sort is a very efficient sorting algorithm with an average time complexity of O(nlogn) and a worst-case time complexity of O(n^2) (if pivot is not chosen optimally). It is also efficient in its best case. 


Related Topics

Swap numbers in C++

Swap numbers Swapping refers to interchanging values between two variables. Swapping is important and easy to understand programming logic in the world of coding. Though it is used in the programming...

4 minutes read.

Features and Use of Pointers in C/C++

What is a pointer? A pointer is mainly used to store the address of another variable. The * operator creates a pointer variable, which points to a data type (like an...

7 minutes read.

Reserved Keywords in C++

What are reserved keywords in C++? There are a few keywords that cannot be used as identifiers as those words are reserved for some other purposes, such keywords are called reserved...

15 minutes read.

Nullptr in C++

What is Nullptr in C++? A null pointer value is represented by the term nullptr. Use a null pointer value to indicate that a native pointer type, inner pointer, or object...

3 minutes read.

Destructor

Let’s discover the C++ destructor, virtual and pure virtual destructors, and when destructors are invoked and their rules in this lesson. Destructors : A member function that destroys an object is known as...

5 minutes read.

Lambda Expression in C++

The lambda expression was introduced in C++ 11. It is used to write the inline function in C++. The code written in lambda expression cannot be reused further. The syntax...

3 minutes read.

C++ Program For FCFS (First Come First Serve)

The most basic scheduling technique is FCFS, often known as "FIFO (First In, First Out)". In this procedure, the first one is utilized and executed first, while the second one...

4 minutes read.

C++ Maximum Index Problem

Given an array A[] of positive integers. We will find the maximum of (j-i) such that i and j are the indexes of A[] and A[i] <= A[j], i<=j For...

5 minutes read.

C++ Bidirectional Iterators

Iterators : Iterators serve as a link between algorithms and STL containers, allowing the data inside the container to be modified. They let you to iterate through the container, access and...

3 minutes read.

Structure Sorting (By Multiple Rules) in C++

To understand the concept of Structure Sorting (By Multiple Rules) in C++, it is recommended to know the Structures concept in the C++ programming language. Here the scenario is pretty...

3 minutes read.

Pointer to Object in C++

What is a pointer? A pointer in C++ is used to point the variable by storing the address of the variable. In C++, to print the address of the variable, we...

4 minutes read.

C++ STL (Standard Template Library)

Introduction C++ is a flexible type and general proposed programming language. So we need a standard library that supports C++. C++ STL (Standard Template Library) is a collection of templates that...

6 minutes read.

Reverse an Array in C++

The many approaches to reverse an array in the C++ programming language will be discussed in this section. The term "reverse of an array" refers to changing the order of...

8 minutes read.

C++ Range-based For Loop

In C++ language, the range-based for loop was added, which is far superior than the ordinary For loop. The implementation of a range-based for loop doesn't really need much code. It's a...

4 minutes read.

Input Iterators in C++

What are input iterators? Input iterators are used in sequence for carrying out input operations where each value is read-only. It is pointed by the iterator and further incremented. All the iterators...

4 minutes read.

Programs to Print Pyramid Patterns in C++

We will explore how to use code to print a variety of patterns utilizing stars (*), numbers (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,.…)  and alphabets...

7 minutes read.

Parameterize Constructor

C++ Parameterized Constructor A constructor having parameters is known as parameterize constructor. Parameterize constructor is used to assign different values. Syntax: className(data-type argument){   // Constructor definition   }   className(data-type argument, data-type argument){   // Constructor definition   } A parameterized constructor can be passed values to constructor function in two ways: 1)...

1 minute read.

4-Dimensional Array in C/C++

A four-dimensional (4D) array is an array of three-dimensional (3D) arrays, or in other words we can say that a 4- dimensional array is an array of arrays of arrays...

3 minutes read.

C++ Program to Implement Shell Sort

    C++ Program to Implement Shell Sort shell sort is basically an Insertion Sort variant. In the insertion sort, we only transfer elements ahead of one location. Many movements are involved...

2 minutes read.

Binary Operator Overloading in C++

The Binary Operator Overloading in the C++ programming language will be covered in this part. An operator which comprises two operands to execute a mathematical operation is termed the Binary...

6 minutes read.