Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- using namespace std;
- typedef long long ll;
- int partition(int arr[],int left,int right)
- {
- int x = arr[right]; //initialize comparing value
- int i = left-1;
- //exchanging elements if necessary or exchange with themselves
- for(int j=left;j<=right-1;j++)
- {
- if(arr[j]<x)
- {
- i++;
- swap(arr[i],arr[j]);
- }
- }
- //exchange with compared value to put it on the right place
- swap(arr[i+1],arr[right]);
- return i+1; //return the index
- }
- void quicksort(int arr[],int left,int right)
- {
- //base case
- if(left>=right)
- return;
- //process
- int q = partition(arr,left,right); //partitioning index
- //recursive call
- quicksort(arr,left,q-1);
- quicksort(arr,q+1,right);
- }
- int main()
- {
- #ifndef ONLINE_JUDGE
- freopen("input.txt", "r", stdin);
- freopen("output.txt", "w", stdout);
- #endif
- int n;
- cin >> n; //declaring array size
- int arr[n]; //declaring array
- for(int i=0;i<n;i++)
- cin >> arr[i];
- //calling function
- quicksort(arr,0,n-1);
- //printing array
- for(int i=0;i<n;i++)
- cout << arr[i] << ' ';
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment