你的第一个解决方案将无法工作,它不会对数组进行排序。但第二个方法会起作用,它会将数据从最小到最大排序。有关详细说明,请参见下文:
嘛,后面冒泡排序算法的想法是要经过数据的阵列/集,而比较每对相邻的项目,并交换他们,如果他们是在错误的顺序。重复传递数组/列表直到不需要交换,这表明列表/数组已排序。 时间复杂度:为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