diff --git a/quicksort.cpp b/quicksort.cpp new file mode 100644 index 0000000..c6f44b1 --- /dev/null +++ b/quicksort.cpp @@ -0,0 +1,58 @@ +#include +using namespace std; +int partition(int[], int, int); +void quickSort(int[], int, int); +void displayArray(int[], int); + + +int main() { + int size; + cout << "Enter the size of the vector : "; + cin >> size; + + int* arr = new int[size]; + cout << "Enter the elements of the vector!" << endl; + for (int i = 0; i < size; i++) { + cout << "Element " << i+1 << ": "; + cin >> arr[i]; + } + + cout << "---- Vector before quicksort" << endl; + displayArray(arr, size); + quickSort(arr, 0, size - 1); + cout << "++++ Vector after quicksort" << endl; + displayArray(arr, size); + + delete[] arr; + return 0; +} + +int partition(int arr[], int low, int high) { + int pivot = arr[high]; + int i = low - 1; + + for (int j = low; j < high; j++) { + if (arr[j] <= pivot) { + i++; + swap(arr[i], arr[j]); + } + } + swap(arr[i + 1], arr[high]); + return i + 1; +} + +void quickSort(int arr[], int low, int high) { + if (low < high) { + int pivotIndex = partition(arr, low, high); + + quickSort(arr, low, pivotIndex - 1); + quickSort(arr, pivotIndex + 1, high); + } +} + +void displayArray(int arr[], int size) { + for (int i = 0; i < size; i++) { + cout << arr[i] << " "; + } + cout << endl; +}