Skip to content

Commit

Permalink
Create quick_sort.cpp
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
arjunjain8887 authored Oct 7, 2024
1 parent ec3c2e7 commit 82217e8
Showing 1 changed file with 33 additions and 0 deletions.
33 changes: 33 additions & 0 deletions C++_Problems/quick_sort.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
#include <iostream>
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);


0 comments on commit 82217e8

Please sign in to comment.