-
Notifications
You must be signed in to change notification settings - Fork 8
/
main.cpp
55 lines (44 loc) · 1.41 KB
/
main.cpp
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
#include <ctime>
#include <vector>
#include <iostream>
void insertionSort(std::vector<int>& arr) {
for (size_t i = 1; i < arr.size(); ++ i) {
size_t tmp = arr[i];
size_t j; // save the location where `tmp` should be inserted.
for (j = i; j > 0 && arr[j - 1] > tmp; -- j) {
arr[j] = arr[j - 1];
}
arr[j] = tmp;
}
}
std::vector<int> generateRandomArray(size_t length, size_t rangeFrom, size_t rangeTo);
void printArray(const std::vector<int>& arr);
int main() {
size_t dataSize = 20;
size_t rangeFrom = 1;
size_t rangeTo = 10000;
auto arr = generateRandomArray(dataSize, rangeFrom, rangeTo);
std::cout << "Original array:" << std::endl;
printArray(arr);
insertionSort(arr);
std::cout << "Sorted array:" << std::endl;
printArray(arr);
return 0;
}
/* Randomly generate an array with the `dataSize`, which is from `rangeFrom` to `rangeTo` */
std::vector<int> generateRandomArray(size_t dataSize, size_t rangeFrom, size_t rangeTo) {
size_t range = rangeTo - rangeFrom + 1;
srand(time(nullptr));
std::vector<int> arr(dataSize);
for (size_t i = 0; i < dataSize; ++ i) {
arr[i] = rand() % range + rangeFrom;
}
return arr;
}
/* formatted output array */
void printArray(const std::vector<int>& arr) {
for (const auto& num: arr) {
std::cout << num << " ";
}
std::cout << std::endl;
}