Implement Quick Sort algorithm in C++
Code
// quick sort#include <iostream>using namespace std;void quicksort(int arr[], int first, int last){int i, j, pivot, temp;if (first < last){pivot = first;i = first;j = last;while (i < j){while (arr[i] <= arr[pivot] && i < last){i++;}while (arr[j] > arr[pivot]){j--;}if (i < j){temp = arr[i];arr[i] = arr[j];arr[j] = temp;}}temp = arr[pivot];arr[pivot] = arr[j];arr[j] = temp;quicksort(arr, first, j - 1);quicksort(arr, j + 1, last);}}int main(){int n, i, j, temp;int arr[50];cout << "Enter the size of array: ";cin >> n;cout << "Enter the elements of array: " << endl;for (i = 0; i < n; i++){cin >> arr[i];}quicksort(arr, 0, n - 1);cout << "Sorted array: ";for (i = 0; i < n; i++){cout << arr[i] << " ";}cout << endl;return 0;}
Output
Enter the size of array: 6
Enter the elements of array:
5
32
76
34
8
44
Sorted array: 5 8 32 34 44 76
0 Comments
Post a Comment