Implement Wirth algorithm

It's fast!
This commit is contained in:
karl 2020-10-17 00:43:28 +02:00
parent 35488b55cd
commit 1f685a95f2
2 changed files with 33 additions and 3 deletions

28
Wirth.h
View File

@ -1,3 +1,31 @@
#pragma once
// http://ndevilla.free.fr/median/median/index.html
size_t getWirthKthSmallest(std::vector<size_t> a, size_t k)
{
size_t l = 0;
size_t m = a.size() - 1;
while (l < m) {
size_t x = a[k];
size_t i = l;
size_t j = m;
do {
while (a[i] < x) i++;
while (x < a[j]) j--;
if (i <= j) {
std::swap(a[i], a[j]);
i++;
j--;
}
} while (i <= j);
if (j < k) l = i;
if (k < i) m = j;
}
return a[k];
}

View File

@ -7,6 +7,7 @@
#include "MedianQuicksort.h"
#include "MedianOfMedians.h"
#include "RandomizedSelect.h"
#include "Wirth.h"
// TODO:
// - combine partition function
@ -48,7 +49,7 @@ int main(int argc, char** argv)
size_t idxMed = (numbers.size() - 1) / 2;
std::cout << "idx median = " << idxMed << " of " << numbers.size() << std::endl;
// vollständige Sortierung mit Quicksort und Ausgabe des mittleren Elements
// vollst<EFBFBD>ndige Sortierung mit Quicksort und Ausgabe des mittleren Elements
Timing::getInstance()->startRecord("quicksort");
std::cout << "quicksort median: " << getQuicksortMedian(numbers, idxMed) << std::endl;
Timing::getInstance()->stopRecord("quicksort");
@ -91,8 +92,9 @@ int main(int argc, char** argv)
Timing::getInstance()->stopRecord("array median of medians");
// noch ein ein weiterer Median - Algorithmus weil wir so cool sind
std::vector<size_t> numbers_wirth(numbers); // Copy because wirth works in-place
Timing::getInstance()->startRecord("wirth");
// TODO: implement
std::cout << "wirth kth element: " << getWirthKthSmallest(numbers_wirth, idxMed) << std::endl;
Timing::getInstance()->stopRecord("wirth");
// Verwendung des C++ STL function templates nth_element