0% found this document useful (0 votes)
2 views

Quick Sort Code

quick sort

Uploaded by

areebejaz030
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Quick Sort Code

quick sort

Uploaded by

areebejaz030
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

Quick Sort Code

#include <iostream>
using namespace std;

// Function to perform the partitioning step of Quick Sort


int partition(int arr[], int low, int high) {
// Choosing the last element as the pivot
int pivot = arr[high];
int i = (low - 1); // Index of smaller element

// Rearranging elements based on the pivot


for (int j = low; j <= high - 1; j++) {
// If current element is smaller than or equal to the pivot
if (arr[j] <= pivot) {
i++; // Increment index of smaller element
swap(arr[i], arr[j]); // Swap arr[i] and arr[j]
}
}
// Place the pivot in its correct position
swap(arr[i + 1], arr[high]);
return (i + 1); // Return the index of the pivot
}

// Quick Sort function (recursive)


void quickSort(int arr[], int low, int high) {
if (low < high) {
// Find pivot index
int pi = partition(arr, low, high);

// Recursively sort the elements before and after the pivot


quickSort(arr, low, pi - 1); // Before pivot
quickSort(arr, pi + 1, high); // After pivot
}
}

// Function to print the array


void printArray(int arr[], int size) {
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
cout << endl;
}

int main() {
// Example array
int arr[] = {10, 7, 8, 9, 1, 5};
int n = sizeof(arr) / sizeof(arr[0]);

cout << "Original array: ";


printArray(arr, n);
// Perform Quick Sort
quickSort(arr, 0, n - 1);

cout << "Sorted array: ";


printArray(arr, n);

return 0;
}

The End.

You might also like