Skip to content

Commit

Permalink
Merge pull request #60 from Shoaib237124/Quick-sort-Algo
Browse files Browse the repository at this point in the history
Quick Sort Algo in c++
  • Loading branch information
gautamankoji authored Oct 29, 2024
2 parents 14cd3fc + 93328d8 commit b7cd39b
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 0 deletions.
41 changes: 41 additions & 0 deletions Sorting algo/Quick sort.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
#include <iostream>
#include <vector>

// Partition function for Quick Sort
int partition(std::vector<int>& arr, int low, int high) {
int pivot = arr[high]; // Select the pivot element
int i = low - 1;

for (int j = low; j < high; j++) {
if (arr[j] < pivot) {
i++;
std::swap(arr[i], arr[j]);
}
}
std::swap(arr[i + 1], arr[high]);
return i + 1;
}

// Quick Sort recursive function
void quickSort(std::vector<int>& arr, int low, int high) {
if (low < high) {
int pi = partition(arr, low, high);

quickSort(arr, low, pi - 1); // Recursively sort left half
quickSort(arr, pi + 1, high); // Recursively sort right half
}
}

// Main function to test the Quick Sort algorithm
int main() {
std::vector<int> arr = {10, 7, 8, 9, 1, 5};
int n = arr.size();
quickSort(arr, 0, n - 1);

std::cout << "Sorted array: ";
for (int num : arr) {
std::cout << num << " ";
}
return 0;
}

18 changes: 18 additions & 0 deletions Sorting algo/README.md.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# Quick Sort Algorithm

## Overview
Quick Sort is a divide-and-conquer sorting algorithm. It works by selecting a pivot element and partitioning the array around the pivot such that elements less than the pivot are on the left, and elements greater are on the right. The algorithm then recursively applies the same process to the subarrays.

## Time Complexity
- Best Case: **O(n log n)** - Occurs when the pivot divides the array into two nearly equal halves.
- Average Case: **O(n log n)** - Expected on average for a randomly ordered array.
- Worst Case: **O(n^2)** - Occurs when the pivot selection consistently produces one-sided splits, such as with a sorted array.

## Space Complexity
- Space Complexity: **O(log n)** - For the recursive call stack in the best and average cases. However, it can go up to **O(n)** in the worst case due to unbalanced partitions.

## How to Run
Compile and run `quick_sort.cpp` using a C++ compiler:
```bash
g++ quick_sort.cpp -o quick_sort
./quick_sort

0 comments on commit b7cd39b

Please sign in to comment.