你的第一個解決方案將無法工作,它不會對數組進行排序。但第二個方法會起作用,它會將數據從最小到最大排序。有關詳細說明,請參見下文:
嘛,後面冒泡排序算法的想法是要經過數據的陣列/集,而比較每對相鄰的項目,並交換他們,如果他們是在錯誤的順序。重複傳遞數組/列表直到不需要交換,這表明列表/數組已排序。 時間複雜度:爲O(n^2)。和我們將使用原始數組的空間。請使用以下數組說明上述段落中的說明:
//array of integer to be sorted
int[] arrayToSort=new int[]{1,7,81,2,-2,9,9,6,-6};
//repeat until we're done sorting
while (true){
//flag to check if we did swap number(s)
boolean didSort=false;
/*
* this inner loop is being used to find numbers that need to be
* swapped and then help in swapping them
*/
for(int count=0;count<arrayToSort.length-1;count++){
//check if we need to swap
if(arrayToSort[count]>arrayToSort[count+1]){
int temp=arrayToSort[count+1];
arrayToSort[count+1]=arrayToSort[count];
arrayToSort[count]=temp;
//set our swap flag so that we will know that we did swap
didSort=true;
}
}
//check we did a swap in our last inner loop iteration if not will
//be done sorting, then break the outer loop
if(!didSort){
break;
}
}
//let's print the sorted array.
for(int i=0;i<arrayToSort.length;i++){
System.out.print(arrayToSort[i]+", ");
}
第一個不會對數組進行排序。 – sgarizvi 2013-02-18 11:08:12
第二個更好,因爲它對給定的數組進行排序。 – 2013-02-18 11:16:47