simple bubble sort
👍 g++ -std=c++11 program64.cpp
👍 ./a.out 7 1
153 181 183 205 246 334 656
👍 ./a.out 7 1
294 313 334 450 557 599 844
👍 ./a.out 7 0
3 1 4 1 5 9 2
1 1 2 3 4 5 9
👍 cat program64.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 bubble(T a[], int l, int r)
{
for (int i = l; i < r; i++)
for (int j = r; j > i; 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++; }
bubble(a, 0, N-1);
for (i = 0; i < N; i++) cout << a[i] << " ";
cout << endl;
}
ch 6.4 Bubble Sort p278 of