冒泡排序算法需要遍历几次数组。在每次遍历中,比较连续相邻的元素。如果某一对元素是降序,则互换它们的值;否则,保持不变。第一次遍历之后,最后一个元素成为数组中的最大数。第二次遍历之后,倒数第二个元素成为数组中的第二大数。整个过程持续到所有元素都已排好序为至。其时间复杂度为O(n*n).
public class BubbleSort {
public static void main (String[] args) {
double[] myList = {5.0, 4.4, 1.9, 2.9, 3.4, 2.9, 3.5};
System.out.println("My list before sort is: ");
//prints the original list
printList(myList);
//bubbleSort(myList);
bubble_sort(myList);
//prints the sorted list
System.out.println("My list after sort is: ");
printList(myList);
}
public static void printList(double[] list) {
for (int i = 0; i < list.length; i++)
System.out.println(list[i]+"\t");
System.out.println();
}
public static void bubble_sort(double list[]){
int i, j;
double t;
for(i=0; i<list.length-1; i++) // i 控制扫描次数
for(j=0; j<list.length-1-i; j++) // j 控制第i 次扫描时下标的变化
if(list[j]>list[j+1]){
t=list[j];
list[j]=list[j+1];
list[j+1]=t;
}
}
public static void bubbleSort(double[] list) {
boolean changed = true;
do {
changed = false;
for (int j = 0; j < list.length - 1; j++)
if (list[j] > list[j+1]) {
//swap list[j] wiht list[j+1]
double temp = list[j];
list[j] = list[j + 1];
list[j + 1] = temp;
changed = true;
}
} while (changed);
}
public static void bubbleSort(int[] list) {
boolean needNextPass = true;
for (int k = 1; k < list.length && needNextPass; k++) {
// Array may be sorted and next pass not needed
needNextPass = false;
for (int i = 0; i < list.length - k; i++) {
if (list[i] > list[i + 1]) {
// Swap list[i] with list[i + 1]
int temp = list[i];
list[i] = list[i + 1];
list[i + 1] = temp;
needNextPass = true; // Next pass still needed
}
}
}
}
/** The method for sorting the numbers */
public static <E extends Comparable<E>> void bubbleSort(E[] list) {
boolean needNextPass = true;
for (int k = 1; k < list.length && needNextPass; k++) {
// Array may be sorted and next pass not needed
needNextPass = false;
for (int i = 0; i < list.length - k; i++) {
if (list[i].compareTo(list[i + 1]) > 0) {
// Swap list[i] with list[i + 1]
E temp = list[i];
list[i] = list[i + 1];
list[i + 1] = temp;
needNextPass = true; // Next pass still needed
}
}
}
}
}