-
Notifications
You must be signed in to change notification settings - Fork 466
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #133 from arjunjain8887/patch-1
Create quick_sort.cpp
- Loading branch information
Showing
1 changed file
with
33 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
|
||
|