冒泡排序的基本思想是:每次比较两个相邻的元素,如果它们的顺序关系不符合想要达到的顺序则交换它们的顺序。
冒泡排序的原理是:每趟只能确定将一个数归位,即第一趟只能确定将末位的数字归位,第二趟只能将倒数第二位的数字归位,以此类推,只到第二位进行归位。
举个栗子:
第一轮 2 5 1 4 3 - 5 2 1 4 3 - 5 2 1 4 3 - 5 2 4 1 3 - 5 2 4 3 1
第二轮 5 2 4 3 1 - 5 2 4 3 1 - 5 4 2 3 1 - 5 4 3 2 1
第三轮 5 4 3 2 1 - 5 4 3 2 1 - 5 4 3 2 1
第四轮 5 4 3 2 1 - 5 4 3 2 1
下面是冒泡排序的实现:
import java.util.Scanner;
public class BubbleSort {
public static void main(String[] args) {
//初始化
final int NUMBERS_OF_ELEMENTS = 100;
Scanner input = new Scanner(System.in);
int counts;
int[] array = new int[NUMBERS_OF_ELEMENTS];
//输入需排序的数字
System.out.println("请输入需排序的数字个数:\n");
counts = input.nextInt();
System.out.println("请输入需排序的数字:\n");
for(int i = 0; i < counts; i++)
array[i] = input.nextInt();
//冒泡排序
int[] result = bubbleSort(array,counts);
for(int i = 0; i < result.length; i++)
System.out.print(result[i] + " ");
input.close();
}
//冒泡算法的实现
public static int[] bubbleSort(int[] array, int n){
int temp;
int result[] = new int[n];
for(int i = 0; i < n - 1; i++){ //控制每次排序循环的次数,只需进行n-1轮排序
for(int j = 1; j < n - i; j++){
//最小的那个“泡泡”就“冒”上来了
if(array[j - 1] < array[j]){
temp = array[j - 1];
array[j - 1] = array[j];
array[j] = temp;
}
}
}
for(int i = 0; i < n; i++)
result[i] = array[i];
return result;
}
}
冒泡排序的核心是双重嵌套循环,缺点是有非常高的时间复杂度,而桶排序的时间复杂度很低,但是需要很大的空间。