|
See the below fig ,
"Quicksort-diagram" by Znupi - Own work. Licensed under Public Domain via Wikimedia Commons.
#include <iostream> using namespace std; void quick_sort(int [],int,int); int main() { int arr[20],n,i; cout << "How many numbers ? \t"; cin >> n; for(i=0 ; i<n ; i++) { cout << "\nEnter number " << i+1 << " :\t"; cin >> arr[i]; } quick_sort(arr,0,n-1); cout << "\n\nThe Sorted Array is:\n\n"; for(i=0 ; i<n ; i++) { cout << arr[i] << "\t"; } return 0; } void quick_sort(int arr[20],int low,int high) { int pivot,j,temp,i; if(low<high) { pivot = low; i = low; j = high; while(i<j) { while((arr[i]<=arr[pivot])&&(i<high)) { 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; quick_sort(arr,low,j-1); quick_sort(arr,j+1,high); } }
Cpp - Quick Sort |