Skip to content

Instantly share code, notes, and snippets.

@Quiark
Created May 8, 2010 09:46
Show Gist options
  • Save Quiark/394469 to your computer and use it in GitHub Desktop.
Save Quiark/394469 to your computer and use it in GitHub Desktop.
#include <algorithm>
#include <cstdlib>
#include <vector>
#include <ctime>
#include <iostream>
using namespace std;
template <typename T>
void straightSelectionSort2(const T& begin, const T& end)
{
if (begin == end)
return;
for (T i = begin; i != end - 1; ++i)
{
T min = i;
// je je ukazatel na položku, se kterou se porovnává
for (T j = i + 1; j != end; ++j)
if (*j < *min)
min = j;
if (*min != *i)
std::iter_swap(min, i);
}
}
template <typename T>
void straightSelectionSortIndex(T &container, int size)
{
for (int i = 0; i != size - 1; ++i)
{
int min = i;
for (int j = i + 1; j != size; ++j)
if (container[j] < container[min])
min = j;
if (container[min] != container[i])
std::swap(container[i], container[min]);
}
}
template <typename T>
void straightSelectionSort3(const T& begin, const T& end)
{
if (begin == end)
return;
// i je ukazatel na první položku nesetříděné části
for (T i = begin; i != end - 1; ++i)
{
std::iter_swap(i, std::min_element(i, end));
}
}
int main()
{
const size_t SIZE = 100000;
std::vector<int> v;
v.reserve(SIZE);
srand(1);
for (size_t i = 0; i < SIZE; ++i)
v.push_back(rand());
clock_t start, stop;
start = clock();
straightSelectionSortIndex(v, v.size()); // varianta index
stop = clock();
cout << static_cast<float>(stop - start) / CLOCKS_PER_SEC << endl;
start = clock();
straightSelectionSort2(v.begin(), v.end()); // varianta sort2
stop = clock();
cout << static_cast<float>(stop - start) / CLOCKS_PER_SEC << endl;
start = clock();
straightSelectionSort3(v.begin(), v.end()); // varianta sort3
stop = clock();
cout << static_cast<float>(stop - start) / CLOCKS_PER_SEC << endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment