a version of insertion sort
👍 g++ -std=c++11 program61.cpp
👍 ./a.out 7 1
203 210 250 305 460 528 709
👍 ./a.out 7 0
3 4 2 54 52 3 1
1 2 3 3 4 52 54
👍 cat program61.cpp
#include <iostream>
using namespace std;
template <typename T>
void exch(T &a, T &b)
{ T t = a; a = b; b = t; }
template <typename T>
void compexch(T &a, T &b)
{ if (b < a) exch(a, b); }
template <typename T>
void sort(T a[], int l, int r)
{
for( int i = l+1; i <= r; i++)
for (int j = i; j > l; j--)
compexch(a[j-1], a[j]);
}
int main(int argc, char *argv[])
{
int i, N = atoi(argv[1]),
sw = atoi(argv[2]);
int *a = new int[N];
srand(time(0));
if (sw)
for (i = 0; i < N; i++)
a[i] = 1000*(1.0*rand()/RAND_MAX);
else
{ N = 0; while (cin >> a[N]) N++; }
sort(a, 0, N-1);
for (i = 0; i < N; i++) cout << a[i] << " ";
cout << endl;
}
ch 6.1 Rules of the Game p268 of