原理:比较两个相邻的元素,将值大的元素交换至右端。
思路:依次比较相邻的两个数,将比较小的数放在前面,比较大的数放在后面。
- 第一次比较:首先比较第一和第二个数,将小数放在前面,将大数放在后面。
- 比较第2和第3个数,将小数 放在前面,大数放在后面。
- 如此继续,知道比较到最后的两个数,将小数放在前面,大数放在后面,重复步骤,直至全部排序完成
- 在上面一趟比较完成后,最后一个数一定是数组中最大的一个数,所以在比较第二趟的时候,最后一个数是不参加比较的。
- 在第二趟比较完成后,倒数第二个数也一定是数组中倒数第二大数,所以在第三趟的比较中,最后两个数是不参与比较的。
- 依次类推,每一趟比较次数减少依次
例一:
public class BubbleSort {
public static void main(String[] args) {
int[] arr = { 23, 41, 63, 17, 39, 22, 44, };
System.out.println("排序前的数组为:");
for(int num:arr){
System.out.println(num+" ");
}
for (int i = 0; i < arr.length; i++) {
for(int j = 0; j < arr.length-1-i; j++){
if(arr[j] > arr[j+1]){
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
System.out.println();
System.out.println("排序后的数组为:");
for(int num:arr){
System.out.println(num+" ");
}
}
}
输出结果:
排序后的数组为:
17 22 23 39 41 44 63
例二:
可自行输入数组,控制数组长度
导包 import java.util.Scanner;
public class BubbleSort2 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = 5; //可输入的数组长度
int a[] = new int[n];
for(int i=0;i<n;i++){
a[i] = sc.nextInt();
}
sort(a,n);
for (int i=0;i<n;i++){
System.out.println(a[i]+" ");
}
}
public static void sort(int a[],int n){
for(int i = 1; i <= n; i++){// n-1的元素排序,第n个自动成序
for (int j = 0; j < n- i; j++) {// n-i个未成序位置
if(a[j]<a[j+1]){
int t = a[j];
a[j] = a[j + 1];
a[j + 1] = t;
}
}
}
}
}