# 第七章第十八题（冒泡排序）（Bubble sort）

• **7.18（冒泡排序）使用冒泡排序算法编写一个排序方法。冒泡排序算法遍历数组几次。在每次遍历中，对相邻的两个元素进行比较。如果这一对元素是降序，则交换他们的值；否则，保持不变。由于较小的值像气泡一样逐渐“浮向”顶部，同时较大的值“沉向”底部，所以，这种技术称为冒泡排序法或下沉排序法。编写一个测试程序，读取10个double型的值，调用这个方法，然后显示排好序的数字。
**7.18（Bubble sort）Use bubble sort algorithm to write a sort method. Bubble sort algorithm traverses the array several times. In each traversal, two adjacent elements are compared. If the pair of elements is in descending order, their values are exchanged; otherwise, they remain unchanged. Because smaller values “float” to the top like bubbles, while larger values “sink” to the bottom, this technique is called bubble sorting or sink sorting. Write a test program, read 10 double type values, call this method, and then display the ordered number.

• 参考代码：

package chapter07;

import java.util.Scanner;

public class Code_18 {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
double[] list = new double[10];
System.out.print("Enter ten numbers: ");
for(int i=0;i<10;i++){
list[i]=input.nextDouble();
}
bubbleSort(list);
System.out.print("After bubble sort: ");
for(int i=0;i<10;i++)
System.out.print(list[i]+" ");
}
public static void bubbleSort(double[] list){
boolean n = false;
for(int i=0;i<list.length-1;i++){
n = false;
for(int j=list.length-1;j>i;j--){
if(list[j-1]>list[j]){
double tmp = list[j-1];
list[j-1] = list[j];
list[j] = tmp;
n = true;
}
}
if(n == false)
break;
}
}
}


• 结果显示：

Enter ten numbers: 3 4 6 8 2 10 12 5 34 45
After bubble sort: 2.0 3.0 4.0 5.0 6.0 8.0 10.0 12.0 34.0 45.0
Process finished with exit code 0



01-09 1082

03-23 3万+
04-20 344
06-16 537
11-26 562
06-21 366
05-07 19
10-26 422
07-03 27
10-03 11
05-13 169
04-02 77
10-16 142