-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathInsertionSort.cpp
More file actions
55 lines (48 loc) · 1.18 KB
/
InsertionSort.cpp
File metadata and controls
55 lines (48 loc) · 1.18 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
// Techie Delight https://www.techiedelight.com/merge-sort/
#include <iostream>
#include <vector>
#include <cstdlib>
#include <algorithm>
void print(const std::vector<int>& nums)
{
for (auto n : nums) {
std::cout << n << " ";
}
}
std::vector<int> generateRandomNumbers(const int length, const int min, const int max)
{
std::vector<int> nums;
for (int i = 0; i < length; ++i) {
int x = min + (rand() % max - min + 1);
nums.push_back(x);
}
return nums;
}
void insertionSort(std::vector<int>& nums)
{
for (int i = 1; i < nums.size(); ++i) {
int value = nums[i];
int j = i;
while (j > 0 && nums[j - 1] > value) {
nums[j] = nums[j - 1];
j--;
}
nums[j] = value;
}
}
void test(std::vector<int>& nums)
{
std::cout << "Numbers before sorting: ";
print(nums);
insertionSort(nums);
std::cout << "\nNumbers after sorting: ";
print(nums);
std::cout << "\nIs sorted: " << std::boolalpha << std::is_sorted(nums.begin(), nums.end());
std::cout << "\n";
}
int main()
{
std::vector<int> nums = generateRandomNumbers(20, -1000, 1000);
test(nums);
return 0;
}