Table of contents | |
Introduction | |
Understanding Quick Sort | |
Quick Sort Implementation in C++ | |
Sample Problems |
Sorting is a fundamental operation in computer science, and one of the commonly used sorting algorithms is Quick Sort. It is an efficient and widely adopted algorithm for sorting elements in an array. In this article, we will explore Quick Sort in DSA (Data Structures and Algorithms) using C++. We'll cover the basic concept, step-by-step implementation, and provide multiple examples to help you understand the algorithm better. So, let's get started!
Let's walk through the implementation of Quick Sort in C++ step by step.
Step 1: Choosing the Pivot
Step 2: Partitioning the Array
Step 3: Recursive Sorting
Let's take a look at the C++ code implementation of Quick Sort:
#include <iostream>
// Function to swap two elements
void swap(int* a, int* b) {
int temp = *a;
*a = *b;
*b = temp;
}
// Partitioning the array and returning the pivot index
int partition(int arr[], int low, int high) {
int pivot = arr[high]; // Choosing the pivot as the rightmost element
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);
}
// Quick Sort implementation
void quickSort(int arr[], int low, int high) {
if (low < high) {
int pivotIndex = partition(arr, low, high);
quickSort(arr, low, pivotIndex - 1);
quickSort(arr, pivotIndex + 1, high);
}
}
// Function to print an array
void printArray(int arr[], int size) {
for (int i = 0; i < size; i++)
std::cout << arr[i] << " ";
std::cout << std::endl;
}
int main() {
int arr[] = {10, 7, 8, 9, 1, 5};
int n = sizeof(arr) / sizeof(arr[0]);
std::cout << "Original Array: ";
printArray(arr, n);
quickSort(arr, 0, n - 1);
std::cout << "Sorted Array: ";
printArray(arr, n);
return 0;
}
Explanation:
Example Output:
Let's run the code with the example array {10, 7, 8, 9, 1, 5} and see the output:
Original Array: 10 7 8 9 1 5
Sorted Array: 1 5 7 8 9 10
The array is successfully sorted in ascending order using the Quick Sort algorithm.
Problem 1: Sort the following array using Quick Sort: '{25, 10, 32, 1, 8, 14}'.
The sorted array will be: '{1, 8, 10, 14, 25, 32}'.
Problem 2: Sort the array in descending order using Quick Sort: '{15, 27, 3, 19, 12}'.
The sorted array in descending order will be: '{27, 19, 15, 12, 3}'.
Quick Sort is a powerful sorting algorithm that efficiently sorts elements in an array. In this article, we discussed the basic concept of Quick Sort, provided a step-by-step implementation guide in C++, and demonstrated examples to help you understand the algorithm. Remember to choose a suitable pivot and carefully implement the partitioning process. Quick Sort is widely used in practice due to its simplicity and efficiency.
153 videos|115 docs|24 tests
|
|
Explore Courses for Software Development exam
|