answer for ace

12 views
Skip to first unread message

Steven_Tian

unread,
Dec 26, 2010, 5:47:08 AM12/26/10
to Good Ideas
public class BubbleSort {
public static void main(String[] args) {
int[] ints = { 5, 4, 2, 9, 7,11,1 };
boolean flag=false;
print(0, ints);
int times=0;
for (int i = 1; i < ints.length + 1; i++) {
for (int j = 0; j < ints.length - 1; j++) {
if (ints[j] > ints[j + 1]) {
flag=true;
int temp = ints[j];
ints[j] = ints[j + 1];
ints[j + 1] = temp;
i=1;
times++;
break;
}
}
if(flag==true){
print(times, ints);
System.out.println("\n");
flag=false;
}else if(flag==false){
break;
}
}
}

public static void print(int times, int[] ints) {
if (times == 0) {
System.out.print("原始資料:");
for (int i = 0; i < ints.length; i++) {
System.out.print(ints[i] + " ");
}
System.out.print("\n");
System.out.print("------------------------");
System.out.print("\n");
} else {
System.out.print("第" + times + "次排序: ");
for (int i = 0; i < ints.length; i++) {
System.out.print(ints[i] + " ");
}

}
}
}
Reply all
Reply to author
Forward
0 new messages