Quote:
Originally Posted by alex001
The following is a block of code from a book. It is part of an alphabetization program for a string of words in a paragraph earlier in the program. I get how the program works but I don't understand the following:
// Sort the array of words
String temp = null;
boolean exchange = true;
while(exchange) {
exchange = false;
for(int i = 1 ; i < words.length ; ++i) {
if(words[i-1].compareTo(words[i]) > 0) {
temp = words[i];
words[i] = words[i-1];
words[i-1] = temp;
exchange = true;
}
}
}
// If exchange is set to false then does the rest of the code block execute?
Thank you for your time.
|
================================================== ======
I'm a beginner too, but i think is like this:
String temp = null; //this is an auxiliar variable, that helps to interchange the words, once they are found not in order
boolean exchange = true; // this bool variable assume that the whole phrase is not in alphabetical order
while(exchange) { // while the phrase is not in alphabetical order...
exchange = false; //change the value of exchange
for(int i = 1 ; i < words.length ; ++i) { // loop through phrase
if(words[i-1].compareTo(words[i]) > 0) { //starts with the first word("words[i-1] - which we found him at index 0), and compare him with the next one(the one at index 1). If the integer value returned is positive, means that the first word is greater alphabeticaly than the second word, so we must interchange the words between them. If the integer value returned is negative, means that the first word is less alphabeticaly than the second word. If the integer is 0, means that the two words are equal.
temp = words[i]; // the auxiliar value temp equals second word
words[i] = words[i-1]; // second word equals first word
words[i-1] = temp; // first word equals temp value
exchange = true;
}
}
}
Hope I'm not wrong! GL