3.8 Sample algorithms 83
In thebubble-sortalgorithm, we first find the highest number, and put
it at the bottom of the list. This is done by comparing the first number with
the second number and swapping positions if necessary, then comparing the
second with the third number and swapping positions if necessary, and repeating
the comparisons all the way to the bottom. In the second step, we find the
second-largest number and put it in the penultimate position using a similar
method. In this fashion, light numbers “bubble up” to the top. The algorithm
is implemented in the following code contained in the filebsort.cc:
#include<iostream>
#include<iomanip>
using namespace std;
int main()
{
const int n=5;
float save, x[n+1]={0.0, -0.5, -0.9, 0.3, 1.9, -0.3};
int Istop, i, k;
//--- bubble sort:
k = n-1; // number of comparisons
do{
Istop = 1; // will stop if Iflag 1
for (i=1;i<=k;i++) // compare
{
if(x[i]>x[i+1])
{save = x[i]; // swap
x[i]=x[i+1];
x[i+1] = save;
Istop = 0; // an exchange occurred; do not stop
}
}
k--; // reduce the number of comparisons
}
while(Istop==0);
//--- print the sorted array:
for (i=1;i<=n;i++)
{
cout << setw(5) << right << x[i] << endl;
};
return 0;
}