您的第一个解决方案将不起作用,它不会对数组进行排序。但是第二个会起作用,它将从最小到最大对数据进行排序。有关更多说明,请参见下文:
嗯,冒泡排序算法背后的想法是遍历数据的数组/集合,同时比较每对相邻的项目,如果它们的顺序错误则交换它们。重复遍历数组/列表,直到不需要交换,这表明列表/数组已排序。时间复杂度: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]+", ");
}