-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinsertion-sort.cpp
More file actions
78 lines (74 loc) · 1.94 KB
/
Copy pathinsertion-sort.cpp
File metadata and controls
78 lines (74 loc) · 1.94 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#include <iostream>
#include <vector>
#include <chrono>
#include <random>
#include <sstream>
#include <stdexcept>
#include <algorithm>
void print_vector(const std::vector<int>& numbers)
{
for(unsigned int i = 0 ; i < numbers.size();++i)
{
std::cout << numbers[i] << '\n';
}
}
void insertion_sort(std::vector<int>& numbers)
{
for(unsigned int current_index = 1; current_index < numbers.size();++current_index)
{
int key = numbers[current_index];
int previous_index = current_index - 1;
while(previous_index >= 0 && numbers[previous_index] > key)
{
numbers[previous_index+1] = numbers[previous_index]; // swap current number with previous number;
--previous_index;
}
numbers[previous_index + 1] = key;
}
}
void compare(const std::vector<int> numbers)
{
std::vector<int> numbers_copy = numbers;
std::sort(numbers_copy.begin(),numbers_copy.end());
if(std::equal(numbers.begin(),numbers.end(),numbers_copy.begin()))
{
std::cout << "all match \n";
}
else
{
std::cout << "not all match \n";
}
}
void generate_random_number(std::vector<int>& numbers,int amount_generated)
{
unsigned long int seed = std::chrono::system_clock::now().time_since_epoch().count();
std::mt19937 gen(seed);
std::uniform_int_distribution<int> distribution(0,9);
for(int i = 0; i < amount_generated; ++ i)
{
numbers.push_back(distribution(gen));
}
}
int main(int argc, char* argv[])
{
try
{
std::vector<int> numbers;
std::istringstream ss(argv[1]);
int iterations;
if(!(ss >> iterations))
{
throw std::runtime_error("could not convert input number");
}
generate_random_number(numbers,iterations);
print_vector(numbers);
std::cout << "-------------------- \n";
insertion_sort(numbers);
print_vector(numbers);
compare(numbers);
}
catch(std::exception& e)
{
std::cerr << "runtime error: " << e.what() << '\n';
}
}