Programming and Graphics

(Kiana) #1

84 Introduction to C++ Programming and Graphics


The output of the code is:


-0.9
-0.5
-0.3
0.3
1.9

Selection sort


In theselection-sortalgorithm, we perform only one swap per pass. In
the first pass, we identify the minimum of all elements and put it at the top. In
the second pass, we identify the minimum of all elements except for the first,
and put it in the second position. In the last pass, we identify the minimum of
the last two elements. The implementation of the algorithm is:


/*---------selection sort---------*/

int minpos; float save;

for (int pass=1; pass<n; pass++)
minpos = pass;
for (i=pass+1;i<=n;i++) // compare
{
if(x[i]<x[minpos])
{
minpos=i;
}
save = x(pass);
x(pass) = x(minpos);
x(minpos) =save;
}
}

Alphabetizing a list


The sorting algorithm can be used verbatim to alphabetize a list of names.
The only difference is that the float vectorx[i]is declared as an array of strings
defined, for example, as:


x[1]="Johnson";
x[2]="Brown";
x[3]="Smith";
x[4]="Wu";
x[5]="Yang";
Free download pdf