1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
|
//========================================================= bubbleSortRange
// After a pass in bubble sort, it's only necessary to sort from just
// below the first exchange (small values may move lower)
// to just before the last exchange (largest values won't move higher).
// Everything that wasn't exchanged must be in the correct order.
// After each pass, the upper and lower bounds for the next pass are
// set from the positions of the first and last exchanges on prev pass.
void bubbleSortRange(int x[], int n) {
int lowerBound = 0; // First position to compare.
int upperBound = n; // First position NOT to compare.
//--- Continue making passes while there is a potential exchange.
while (lowerBound <= upperBound) {
int firstExchange = n; // assume impossibly high index for low end.
int lastExchange = -1; // assume impossibly low index for high end.
//--- Make a pass over the appropriate range.
for (int i=lowerBound; i<upperBound; i++) {
if (x[i] > x[i+1]) {
//--- exchange elements
int temp = x[i]; x[i] = x[i+1]; x[i+1] = temp;
//--- Remember first and last exchange indexes.
if (i<firstExchange) { // true only for first exchange.
firstExchange = i;
}
lastExchange = i;
}
}
//--- Prepare limits for next pass.
lowerBound = firstExchange-1;
if (lowerBound < 0) {
lowerBound = 0;
}
upperBound = lastExchange;
}
}//end bubbleSortRange
The text from the above example can be selected, copied, and pasted into an editor.
|