排序算法---最常见的冒泡排序

xiaoxiao2021-02-28  57

冒泡排序

冒泡排序应该是我们最早接触的算法,没有之一。 冒泡排序的基本思想是:每次比较两个相邻的元素,如果它们的顺序错误就把它们交换过来。 如图,从大到小排序,展示了12这个最小的数字是如何排到最后的:

Java代码实现

public class BubbleSort { public static void main(String[] args) { System.out.println("输入排序的个数n:"); Scanner input = new Scanner(System.in); int n = input.nextInt(); int array[] = new int[n]; System.out.println("请输入要排序的数字:"); for (int i = 0; i < n; i++) { array[i] = input.nextInt(); } //核心的双重循环 for (int i = 1; i < n -1; i++) { for (int j = 0; j < n - i; j++) { if (array[j] < array[j + 1]) { int t = array[j]; array[j] = array[j + 1]; array[j+1] = t; } } } System.out.println("排序结果为:"); for (int i = 0; i < n; i++) { System.out.print(array[i] + " "); } } }

测试结果截图

时间复杂度

冒泡排序的核心部分是双重嵌套循环。不难看出冒泡排序的时间复杂度是O(n^2)。 这是一个非常高的时间复杂度,所以冒泡的效率并不高。

转载请注明原文地址: https://www.6miu.com/read-84522.html

最新回复(0)