Skip to content

Commit 9117876

Browse files
authored
Merge pull request #133 from arjunjain8887/patch-1
Create quick_sort.cpp
2 parents 4436051 + 82217e8 commit 9117876

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

C++_Problems/quick_sort.cpp

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
#include <iostream>
2+
using namespace std;
3+
4+
// Function to swap two elements
5+
void swap(int& a, int& b) {
6+
int temp = a;
7+
a = b;
8+
b = temp;
9+
}
10+
11+
// Function to partition the array
12+
int partition(int arr[], int low, int high) {
13+
int pivot = arr[high]; // Choose the last element as the pivot
14+
int i = low - 1; // Pointer for the smaller element
15+
16+
for (int j = low; j < high; j++) {
17+
// If the current element is smaller than or equal to the pivot
18+
if (arr[j] <= pivot) {
19+
i++; // Increment the index of the smaller element
20+
swap(arr[i], arr[j]); // Swap the elements
21+
}
22+
}
23+
swap(arr[i + 1], arr[high]); // Swap the pivot element with the element at i + 1
24+
return i + 1; // Return the partition index
25+
}
26+
27+
// Quick Sort function
28+
void quickSort(int arr[], int low, int high) {
29+
if (low < high) {
30+
// Partition the array and get the pivot index
31+
int pi = partition(arr, low, high);
32+
33+

0 commit comments

Comments
 (0)