👍 g++ -std=c++11 program62.cpp
👍 ./a.out 7 1
23 133 182 217 421 704 792
👍 ./a.out 7 1
16 155 211 217 580 923 948
👍 ./a.out 7 0
3 1 4 1 5 9 3
1 1 3 3 4 5 9
👍 cat program62.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 selection(T a[], int l, int r)
{
for( int i = l; i < r; i++) {
int min = i;
for (int j = i+1; j <= r; j++)
if (a[j] < a[min]) min = j;
exch(a[i], a[min]);
}
}
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++; }
selection(a, 0, N-1);
for (i = 0; i < N; i++) cout << a[i] << " ";
cout << endl;
}
ch 6.2 Selection Sort p273 of