Skip to content

Instantly share code, notes, and snippets.

@WizzyGeek
Last active February 22, 2024 15:46
Show Gist options
  • Save WizzyGeek/5254843c38514b9b97c879fbf20d5845 to your computer and use it in GitHub Desktop.
Save WizzyGeek/5254843c38514b9b97c879fbf20d5845 to your computer and use it in GitHub Desktop.
Insertion sort bench
#include<bits/stdc++.h>
void insertion_sort(std::vector<int> &a) {
for (int i = 1; i < a.size(); i++) {
int b = a[i];
int j = i - 1;
for (; j >= 0 && b < a[j]; j--) {
a[j + 1] = a[j];
}
a[j + 1] = b;
}
}
void insertion_sort_down(std::vector<int> &a) {
for (int i = 1; i < a.size(); i++) {
int b = a[i];
int j = i - 1;
for (; j >= 0 && b > a[j]; j--) {
a[j + 1] = a[j];
}
a[j + 1] = b;
}
}
void display(std::vector<int> &a) {
for (int k : a) std::cout << k << ' ';
std::cout << '\n';
}
int main() {
std::vector<int> sizes {10, 100, 1000, 10000};
std::cout << "size,random_time,bestcase,worstcase\n";
for (int i : sizes) {
std::vector<int> b(i);
std::generate(b.begin(), b.end(), [](){ return std::rand() % 1000; });
auto n1 = std::chrono::high_resolution_clock::now();
insertion_sort(b);
auto d = std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::high_resolution_clock::now() - n1);
n1 = std::chrono::high_resolution_clock::now();
insertion_sort(b);
auto d2 = std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::high_resolution_clock::now() - n1);
std::reverse(b.begin(), b.end());
n1 = std::chrono::high_resolution_clock::now();
insertion_sort(b);
auto d3 = std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::high_resolution_clock::now() - n1);
std::cout << i << ',' << d.count() << ',' << d2.count() << ',' << d3.count() << '\n';
}
}
#include<bits/stdc++.h>
void insertion_sort(std::vector<int> &a) {
for (int i = 1; i < a.size(); i += 2) {
int b = a[i];
int j = i - 2;
for (; j >= 0 && b < a[j]; j -= 2) {
a[j + 2] = a[j];
}
a[j + 2] = b;
}
}
void insertion_sort_down(std::vector<int> &a) {
for (int i = 2; i < a.size(); i += 2) {
int b = a[i];
int j = i - 2;
for (; j >= 0 && b > a[j]; j -= 2) {
a[j + 2] = a[j];
}
a[j + 2] = b;
}
}
void display(std::vector<int> &a) {
for (int k : a) std::cout << k << ' ';
std::cout << '\n';
}
int main() {
std::vector<int> b(10);
std::generate(b.begin(), b.end(), [](){ return std::rand() % 10; });
display(b);
insertion_sort(b);
insertion_sort_down(b);
display(b);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment