This loop works but is there another way to do loop in java?

Hi i’m learning about loops, but is there an easier or another way to do a loop?
I’m just trying different ways to play with the loops so I can understand it better..I would appreciate it.
Thanks very much.

private char guesses [] = new char[26];

void sort() {
    boolean doMore = true;
    while(doMore) {
        doMore = false;
        for(int i = 0; i < guesses.length - 1; i++) {
            if(guesses[i] > guesses[i+1]) {
                char temp = guesses[i];
                guesses[i] = guesses[i+1];
                guesses[i+1] = temp;

                doMore = true;
            }
        }
    }
}

Answer

Nope, this is pretty canonical bubble-sort. The only other way you could change it would be with a “do…while” loop, like such:

void sort() {
boolean doMore;
do {
    doMore = false;
    for(int i = 0; i < guesses.length - 1; i++) {
        if(guesses[i] > guesses[i+1]) {
            char temp = guesses[i];
            guesses[i] = guesses[i+1];
            guesses[i+1] = temp;

            doMore = true;
        }
    }
} while (doMore);

Leave a Reply

Your email address will not be published. Required fields are marked *