class mp{
public static void main(String[] args){
int i=0;
int j=0;
String temp="";
String article=" The Source for Java Developers";
String[] words=article.split("[ ]");
j=words.length;//切分成j个单词
System.out.print("切分成这些单词: ");
for(i=0;i<j;i++){
System.out.print(words[i]+" ");
}
System.out.println();
//下面比较这j个单词
for(int k=0;k<j;k++){
System.out.print("第"+(k+1)+"次比较结果: ");
//下面的程序运行时只比较了一次两个相邻的单词
for(i=0;i<j-1;i++){
if (words[i].compareTo(words[i+1])>0){ //如果words[i]比words[i+1]排序大,则交换两者位置
temp=words[i+1];
words[i+1]=words[i];
words[i]=temp;
}
}
for(i=0;i<j;i++){
System.out.print(words[i]+" ");
}
System.out.println();
}
System.out.print("最终结果为: ");
for(i=0;i<j;i++){
System.out.print(words[i]+" ");
}
}
}
运行结果-----------------------------------------------
切分成这些单词: The Source for Java Developers
第1次比较结果: Source The Java Developers for
第2次比较结果: Source Java Developers The for
第3次比较结果: Java Developers Source The for
第4次比较结果: Developers Java Source The for
第5次比较结果: Developers Java Source The for
最终结果为: Developers Java Source The for