👍 g++ -std=c++11 insertionsort.cpp
👍 ./a.out
50 2 89 0 50 30 99 55 45 97 47
0 2 30 45 47 50 50 55 89 97 99
👍 ./a.out
85 81 29 13 87 48 7 36 93 26 15
7 13 15 26 29 36 48 81 85 87 93
👍 cat insertionsort.cpp
#include <iostream>
#include <random>
using namespace std;
template<typename T>
void insertionsort(T arr[],int n){
for (int i = 1, j; i < n; i++) {
T tmp = arr[i];
for(j=i;j>0 && arr[j-1]>tmp;j--)
arr[j] = arr[j-1];
arr[j] = tmp;
}
}
template<typename T>
void prt(T arr[],int n) {
for (int i = 0; i < n; i++)
cout << arr[i] << ' ';
cout << endl;
}
int main() {
int N = 11, nums[N];
default_random_engine
e(random_device{}());
uniform_int_distribution
d(0, 99);
for (int i = 0; i < N; i++)
nums[i] = d(e);
prt(nums, N);
insertionsort(nums, N);
prt(nums, N);
}
ch 9.1.1 Insertion Sort p493 of