From 82217e8c9a7d85f66c348b787f9b5ba293af084d Mon Sep 17 00:00:00 2001 From: Arjun jain <158755008+arjunjain8887@users.noreply.github.com> Date: Mon, 7 Oct 2024 11:07:23 +0530 Subject: [PATCH] Create quick_sort.cpp MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Quick Sort is a highly efficient sorting algorithm that employs a divide-and-conquer strategy to sort elements in an array or list. Here’s a breakdown of how Quick Sort works: 1.Function swap: A utility function to swap two elements. 2.Function partition: Chooses a pivot (in this case, the last element of the array). Rearranges the array such that elements smaller than the pivot are on the left, and those greater are on the right. Returns the index of the pivot element after partitioning. 3.Function quickSort: Recursively sorts the elements in the array by partitioning it and sorting the two halves. 4.Function printArray: Prints the elements of the array. 5.Main Function: Defines a sample array, prints it, calls the quickSort function, and prints the sorted array. --- C++_Problems/quick_sort.cpp | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 C++_Problems/quick_sort.cpp diff --git a/C++_Problems/quick_sort.cpp b/C++_Problems/quick_sort.cpp new file mode 100644 index 0000000..b746218 --- /dev/null +++ b/C++_Problems/quick_sort.cpp @@ -0,0 +1,33 @@ +#include +using namespace std; + +// Function to swap two elements +void swap(int& a, int& b) { + int temp = a; + a = b; + b = temp; +} + +// Function to partition the array +int partition(int arr[], int low, int high) { + int pivot = arr[high]; // Choose the last element as the pivot + int i = low - 1; // Pointer for the smaller element + + for (int j = low; j < high; j++) { + // If the current element is smaller than or equal to the pivot + if (arr[j] <= pivot) { + i++; // Increment the index of the smaller element + swap(arr[i], arr[j]); // Swap the elements + } + } + swap(arr[i + 1], arr[high]); // Swap the pivot element with the element at i + 1 + return i + 1; // Return the partition index +} + +// Quick Sort function +void quickSort(int arr[], int low, int high) { + if (low < high) { + // Partition the array and get the pivot index + int pi = partition(arr, low, high); + +