Skip to content

Instantly share code, notes, and snippets.

@king1600
Last active July 5, 2017 18:55
Show Gist options
  • Save king1600/c5e55134af61748e1d1a1bc8f2ab8311 to your computer and use it in GitHub Desktop.
Save king1600/c5e55134af61748e1d1a1bc8f2ab8311 to your computer and use it in GitHub Desktop.
c++ quick sort algorithm
#include <algorithm>
#include <iostream>
void _QSort(int *array, int begin, int end) {
if (begin >= end) return;
int i, pivot;
pivot = begin;
for (i = begin + 1; i < end + 1; i++) {
if (array[i] <= array[begin]) {
pivot++;
std::swap(array[i], array[pivot]);
}
}
std::swap(array[pivot], array[begin]);
_QSort(array, begin, pivot - 1);
_QSort(array, pivot + 1, end);
}
void Qsort(int *array, int size, int begin = 0, int end = -1) {
if (end == -1) end = size - 1;
return _QSort(array, begin, end);
}
void printArray(int *array, int size) {
std::cout << "[";
for (int i = 0; i < size; i++)
std::cout << array[i] << (i < size - 1 ? ", " : "]");
std::cout << std::endl;
}
int main() {
int test[] = {5, 6, 2, 4, 6, 8, 7, 3};
int size = sizeof(test) / sizeof(*test);
printArray(test, size);
Qsort(test, size);
printArray(test, size);
}
#include <algorithm>
#include <functional>
template <typename T>
int QPartition
(T* array, std::function<int(T&)> compare, int left, int right)
{
int pivot = (left + right) / 2;
while (left <= right) {
while (compare(array[left]) < compare(array[pivot])) left++;
while (compare(array[right]) > compare(array[pivot])) right--;
if (left <= right) {
std::swap(array[left], array[right]);
left++; right--;
}
}
return left;
}
template <typename T>
void QSort
(T* array, std::size_t size, int left = 0, int right = -1,
std::function<int(T&)> compare = [](T& t){return (int)t;})
{
if (right < 0) right = size - 1;
int pivot = QPartition(array, compare, left, right);
if (left < pivot - 1)
QSort(array, size, left, pivot - 1, compare);
if (right > pivot)
QSort(array, size, pivot, right, compare);
}
Array.prototype.qsort3 = function (sortby) {
let isFunc = obj =>
!!(obj && obj.constructor && obj.call && obj.apply);
if (!isFunc(sortby)) sortby = x => x;
let partition = (array, left, right) => {
let pivot = Math.floor((left + right) / 2);
while (left <= right) {
while (array[left] < array[pivot]) left++;
while (array[right] > array[pivot]) right--;
if (left <= right) {
[array[left], array[right]] = [array[right], array[left]];
left++; right--;
}
}
return left;
};
let qsort = (array, left, right) => {
left = left || 0;
right = right || array.length - 1;
let pivot = partition(array, left, right);
if (left < pivot - 1)
qsort(array, left, pivot - 1);
if (right > pivot)
qsort(array, pivot, right);
return array;
}
return qsort(this.slice());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment