×

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

What does Buffer Flush mean in C++

A buffer flush, to explain simple layman's terms, is nothing but the transfer of computer data which is being stored in a rentable temporary memory of your computer running either...

3 minutes read.

How to concatenate two strings in C++

In the C++ programming language, the concatenation of two or even more strings is covered in this section. The term "string concatenation" refers to a collection of characters that join two...

4 minutes read.

Pthread in C++ Parameters

Pthreads, also known as POSIX threads, is a POSIX standard for multithreading in C/C++. It allows a program to control multiple different threads of execution concurrently. Using pthreads, you can create...

4 minutes read.

Object Slicing in C++

In this article, we will learn about Object slicing. When an object from a derived class is assigned to an object from a base class in C++, these extra attributes...

3 minutes read.

Program to arrange an array in alternate positive and negative numbers

Let’s say, there is given an array arr, arrange the array in such a way that every positive number is followed by a negative number. If there are extra positive...

4 minutes read.

C++ Installation

Let's install C++ setup to start programming in C++. C++ setup contains C++ compiler which is required in your system. There are lots of C++ compilers available, you must choose...

1 minute read.

Depth First Search Program to Traverse a Graph in C++

Depth First Search (DFS) is a technique that is used for transversing the graph. The process of Depth First Search (DFS) starts from the root node and then next comes...

6 minutes read.

std::min in C++

std::min in C++ std::min is specified in the program code, used to calculate the lowest amount that has been transferred. When there's more of someone who returns first of them. It's used...

2 minutes read.

Fast Input and Output in C++

In competitive programming, it's critical to read input as quickly as possible in order to save time. "Warning: Big I / O data, be aware of certain languages (but most...

3 minutes read.

Constexpr in C++

Constexpr is a keyword in C++ that is used to declare variables or functions as compile-time constants. This means that the value of a constexpr variable or the return value...

3 minutes read.

Computing index using Pointers Returned by STL Functions in C++

In this tutorial we will learn how to compute index using pointers which returned by STL functions in C++. Many built-in C++ functions return pointers to memory places that provide...

2 minutes read.

How to make a password program in C++

Before understanding the password program, one must know about a password and why it is required. Password: A password is a word that permits access to somewhere or something. A password...

4 minutes read.

Hybrid Inheritance

C++ Hybrid Inheritance When more than one type of inheritance is combined in single inheritance is called as hybrid inheritance. C++ Hybrid Inheritance Example #include<iostream>   using namespace std;   class Student{       protected:           int rollno;       public:           void getRoll(int a){               rollno=a;           }           void putRoll(void){               cout <<"Roll No: "<< rollno<<endl;           }   };   class Test : public Student{       protected:           float subject1, subject2;       public:           void getMarks(float x, float y){               subject1=x;               subject2=y;           }           void putMarks(void){               cout<< "Marks gain: "<<endl <<"Subject1 =  "<<subject1<<endl<<"Subject2 = "<<subject2 <<endl;           }   };   class Sport{       protected:           float score;       public:           void getScore(float s){               score=s;           }           void putScore(void){               cout<<"Sports score: "<<score<<endl;           }   };   class Result : public Test, public Sport{       float total;       public:           void display(void);   };   void Result:: display(void){       total=subject1+subject2+score;       putRoll();       putMarks();       putScore();       cout<<"Total Score: "<<total<<endl;   }   int main(){       Result stu;       stu.getRoll(10);       stu.getMarks(40,50);       stu.getScore(60);       stu.display();       return 0;   } Output: Roll No: 10 Marks gain: Subject1 = 40 Subject2 = 50 Sports score: 60 Total...

1 minute read.

Vector in C++

Vector in C++ In today’s article, we will be learning all the things about vector in C++ and how vector is different form an array in C++. So basically, vector is very...

3 minutes read.

Use of Inheritance in C++

What is inheritance in c++? Inheritance is fundamental in object-oriented programming (OOP) languages like C++. It allows a programmer to create a new class (called a derived class) that inherits the...

4 minutes read.

C++ Heap Sort

Heapsort is executed on the structure of the heap data. We know heap is a complete tree in binary form. The heap tree can be of two different types: Min-heap,...

3 minutes read.

Dynamic Constructor in C++

Dynamic constructors create dynamic memory by using a dynamic memory allocator new within the constructor. This allows us to initialize objects dynamically. The term dynamic constructor is used when memory...

2 minutes read.

Const Keyword in C++

The const programming language keyword will be covered in this section. The constant value that cannot change during program execution is defined using the const keywords. It implies that once...

9 minutes read.

Program to convert infix to postfix expression in C++

Parentheses are frequently employed in mathematical formulas to make their interpretation easier to understand. However, with computers, parenthesis in an expression might lengthen the time it takes to find a...

7 minutes read.

How to create a directory or folder in C/C++?

A directory is to lists all files and subdirectories in a directory, set of the files will be kept in the directory, which is a location. A subdirectory is a...

5 minutes read.