Created
July 22, 2018 19:53
-
-
Save lykkin/207a57facc2d51d6b1ffb5f2dc61f19a to your computer and use it in GitHub Desktop.
in place quicksort
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <vector> | |
using namespace std; | |
void print(vector<int> a) { | |
for (int el : a) { | |
cout << el << " "; | |
} | |
cout << endl; | |
} | |
void swap(vector<int>& arr, int i, int j) { | |
int temp = arr[i]; | |
arr[i] = arr[j]; | |
arr[j] = temp; | |
} | |
vector<int> in_place_quick_sort(vector<int>& arr, int start, int end) { | |
if (end - start <= 2) { | |
return arr; | |
} | |
int pivot_idx = start + (end - start) / 2; | |
int pivot_val = arr[pivot_idx]; | |
int lcursor = start; | |
int rcursor = pivot_idx + 1; | |
while (lcursor < pivot_idx || rcursor < end) { | |
if (lcursor < pivot_idx) { | |
if (arr[lcursor] > pivot_val) { | |
swap(arr, pivot_idx, lcursor); | |
swap(arr, lcursor, --pivot_idx); | |
} | |
lcursor < pivot_idx ? ++lcursor : --lcursor; | |
} else if (rcursor < end) { | |
if (arr[rcursor] < pivot_val) { | |
swap(arr, pivot_idx, rcursor); | |
swap(arr, rcursor, ++pivot_idx); | |
lcursor++; | |
} | |
rcursor++; | |
} | |
} | |
print(arr); | |
in_place_quick_sort(arr, start, pivot_idx); | |
in_place_quick_sort(arr, pivot_idx, end); | |
return arr; | |
} | |
vector<int> quick_sort(vector<int> arr) { | |
return in_place_quick_sort(arr, 0, arr.size()); | |
} | |
int main() { | |
vector<int> test{300, 4,5,3,8,3,6,7,1,3,1,6,-1,11,232}; | |
print(quick_sort(test)); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment