diff options
author | Derick Huth <derickhuth@gmail.com> | 2016-02-10 11:13:08 -0700 |
---|---|---|
committer | Derick Huth <derickhuth@gmail.com> | 2016-02-10 11:13:08 -0700 |
commit | 1dd03ee01bff2a70e758ce984476527f3ff42c68 (patch) | |
tree | 9731867c7019ec9b6ee111c8fa9f92a92119b5ec /test-chill/unit-tests/cprog/QuickSorter.cc | |
parent | 4631ad76927d433da5d55c3c373a1dfd0f74c9d4 (diff) | |
parent | d68532f2f3ba332199f84818cb047d69a3f33588 (diff) | |
download | chill-1dd03ee01bff2a70e758ce984476527f3ff42c68.tar.gz chill-1dd03ee01bff2a70e758ce984476527f3ff42c68.tar.bz2 chill-1dd03ee01bff2a70e758ce984476527f3ff42c68.zip |
Merge pull request #8 from dhuth/master
w/ python test suite
Diffstat (limited to 'test-chill/unit-tests/cprog/QuickSorter.cc')
-rw-r--r-- | test-chill/unit-tests/cprog/QuickSorter.cc | 83 |
1 files changed, 83 insertions, 0 deletions
diff --git a/test-chill/unit-tests/cprog/QuickSorter.cc b/test-chill/unit-tests/cprog/QuickSorter.cc new file mode 100644 index 0000000..3ade346 --- /dev/null +++ b/test-chill/unit-tests/cprog/QuickSorter.cc @@ -0,0 +1,83 @@ +#include "QuickSorter.h" + +/* Python + +def swap(l, i, k): + v = l[i] + l[i] = l[k] + l[k] = v + print(str(l)) + +def partition(l, start, end): + print("PARTITION {} [{}:{}]".format(l, start, end)) + p_value = l[end] + p_index = end-1 + + for i in range(start, end): + while(i < p_index and l[i] >= p_value): + swap(l, i, p_index) + p_index -= 1 + while(i >= p_index and l[i] < p_value): + swap(l, i, p_index) + p_index += 1 + swap(l, p_index, end) + print("DONE {}|[{}]|{}:{}".format(l[start:p_index], l[p_index], l[p_index+1:end+1], p_value)) + return p_index + +def qsort(l, i, k): + if i < k: + p = partition(l, i, k) + qsort(l,i,p-1) + qsort(l,p+1,k) + +if __name__ == "__main__": + import random as r + x = [int(r.random()*12) for i in range(12)] + print(x) + qsort(x, 0, len(x)-1) + print(x) + +*/ + +static void swap(std::vector<int>& list, int i, int k) { + int v = list[i]; + list[i] = list[k]; + list[k] = v; +} + +static int partition(std::vector<int>& list, int i, int k) { + int pivot_value = list[k]; + int pivot_index = k - 1; + + for(int index = i; index < k; index++) { + while((index < pivot_index) && (list[index] >= pivot_value)) { + swap(list, index, pivot_index); + pivot_index--; + } + while((index >= pivot_index) && (list[index] < pivot_value)) { + swap(list, index, pivot_index); + pivot_index++; + } + } + swap(list, pivot_index, k); + return pivot_index; +} + +static void quicksort(std::vector<int>& list, int i, int k) { + if(i < k) { + int p = partition(list, i, k); + quicksort(list, i, p-1); + quicksort(list, p+1, k); + } +} + +QuickSorter::QuickSorter() { + this->name = std::string("quicksort"); +} + +QuickSorter::~QuickSorter() { +} + +void QuickSorter::sort(std::vector<int>& list) const { + quicksort(list, 0, list.size()-1); +} |