OK, I'll bite. How do you do it in one loop?
for (int ii = 0; ii < n-1; ++ii) {
// ii+1 largest elements end up in their correct position at the end of this loop.
for (int jj = ii; jj < n-1; ++jj) {
if (arr[jj] > arr[jj+1]) {
swap(arr[jj], arr[jj+1]);
}
}
}
One loop: int ii, jj;
for (ii = 0, jj = 0; ii < n-1; ii = ((jj == (n-1)) ? (ii + 1) : ii), jj = ((jj == n-1) ? ii : (jj + 1))) {
// compare and swap as before
}
Unreadable, but it's one loop.EDIT: use code formatting, oops. EDIT 2: add proper conditional for jj update instead of jj = jj + 1.
for (set up initial conditions for both loops;
check the outer loop termination condition;
if the inner loop is done reset the inner loop and advance the outer loop,
if the inner loop is not done advance the inner loop) {
// do the inside of the loop
}