Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- #include <chrono>
- #include <random>
- #include <algorithm>
- #include <iomanip>
- // Custom insertion sort vs standard insertion sort
- // Contact Email [email protected]
- // Created by I.A
- void standardInsertionSort(std::vector<int>& arr) {
- int n = arr.size();
- for (int i = 1; i < n; i++) {
- int key = arr[i];
- int j = i - 1;
- while (j >= 0 && arr[j] > key) {
- arr[j + 1] = arr[j];
- j--;
- }
- arr[j + 1] = key;
- }
- }
- void customJumpSort(std::vector<int>& arr) {
- int n = arr.size();
- for (int i = 1; i < n; i++) {
- int key = arr[i];
- int j = i - 1;
- while (j >= 0 && arr[j] > key) {
- if (j >= 1) {
- arr[j + 1] = arr[j];
- if (arr[j - 1] > key) {
- arr[j] = arr[j - 1];
- j -= 2;
- } else {
- arr[j] = key;
- goto placed;
- }
- } else {
- arr[j + 1] = arr[j];
- j--;
- }
- }
- arr[j + 1] = key;
- placed:;
- }
- }
- int main() {
- const int NUM_ELEMENTS = 32;
- const int NUM_TRIALS = 1000000;
- std::random_device rd;
- std::mt19937 gen(rd());
- std::uniform_int_distribution<> dist(1, 100000);
- double totalStd = 0, totalJump = 0;
- for (int t = 0; t < NUM_TRIALS; ++t) {
- std::vector<int> data1(NUM_ELEMENTS);
- for (int& x : data1) x = dist(gen);
- std::vector<int> data2 = data1;
- // Benchmark Standard
- auto s1 = std::chrono::steady_clock::now();
- standardInsertionSort(data1);
- auto e1 = std::chrono::steady_clock::now();
- totalStd += std::chrono::duration<double>(e1 - s1).count();
- // Benchmark Custom
- auto s2 = std::chrono::steady_clock::now();
- customJumpSort(data2);
- auto e2 = std::chrono::steady_clock::now();
- totalJump += std::chrono::duration<double>(e2 - s2).count();
- // Verify Logic
- if (!std::is_sorted(data2.begin(), data2.end())) {
- std::cout << "CRITICAL ERROR: Custom Sort Failed!" << std::endl;
- return 1;
- }
- }
- // Changed output to Total Time
- std::cout << std::left << std::setw(20) << "Algorithm" << " | " << "Total Time (s)" << std::endl;
- std::cout << "--------------------------------------------" << std::endl;
- std::cout << std::setw(20) << "Standard Insertion" << " | " << std::fixed << std::setprecision(6) << totalStd << std::endl;
- std::cout << std::setw(20) << "Custom insertion Sort" << " | " << std::fixed << std::setprecision(6) << totalJump << std::endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment