冒泡排序
图解
(注:图片来源网络)
Java代码
package suanfa_Ja;import org.apache.hadoop.security.SaslOutputStream;// 基本排序算法,冒泡排序 时间复杂度 O(n^2) 空间复杂度O(1)
public class BubbleSort {public static void bubbleSort(int[] data) {System.out.println("开始排序");int arrayLength = data.length;for (int i = 0; i < arrayLength - 1; i++){boolean flag = false;for (int j = 0; j < arrayLength - 1 - i; j++){if (data[j] > data[j + 1]){int tmp = data[j + 1];data[j + 1] = data[j];data[j] = tmp;flag = true;}}System.out.println(java.util.Arrays.toString(data));if (!flag)break;}}public static void main(String[] args) {int[] data = {12,4,5,-12,23,66,89,11,4,99};System.out.println("排序前:\n" + java.util.Arrays.toString(data));bubbleSort(data);System.out.println("排序后:\n" + java.util.Arrays.toString(data));}}//做了优化后的代码
// 添加一个标志位来记录每次内循环是否有交换操作,如果没有交换操作说明已经有序,可以提前结束排序。
//内循环的终止条件可以根据已经经过的轮数来确定,每一轮外循环都会将最大的元素放到最后,所以
//内循环的比较次数可以逐轮减少。
//添加一个判断数组是否为空或长度为1的情况,这种情况下数组已经是有序的,不需要进行排序。
package com.example;
public class BubbleSort {public static void bubbleSort(int[] data) {if (data == null || data.length <= 1) {return;}System.out.println("开始排序");int arrayLength = data.length;for (int i = 0; i < arrayLength - 1; i++) {boolean flag = false;for (int j = 0; j < arrayLength - 1 - i; j++) {if (data[j] > data[j + 1]) {int tmp = data[j + 1];data[j + 1] = data[j];data[j] = tmp;flag = true;}}System.out.println(java.util.Arrays.toString(data));if (!flag) {break;}}}public static void main(String[] args) {int[] data = {12, 4, 5, -12, 23, 66, 89, 11, 4, 99};System.out.println("排序前:\n" + java.util.Arrays.toString(data));bubbleSort(data);System.out.println("排序后:\n" + java.util.Arrays.toString(data));}
}
代码运行结果:
D:\Java\jdk1.8.0_131\bin\java.exe "-javaagent:D:\idea\IntelliJ IDEA 2021.1.3\lib\idea_rt.jar=51381:D:\idea\IntelliJ IDEA 2021.1.3\bin" -Dfile.encoding=UTF-8 -classpath "D:\idea\IntelliJ IDEA 2021.1.3\lib\idea_rt.jar" com.intellij.rt.execution.CommandLineWrapper C:\Users\Administrator\AppData\Local\Temp\idea_classpath1494763510 suanfa_Ja.BubbleSort
排序前:
[12, 4, 5, -12, 23, 66, 89, 11, 4, 99]
开始排序
[4, 5, -12, 12, 23, 66, 11, 4, 89, 99]
[4, -12, 5, 12, 23, 11, 4, 66, 89, 99]
[-12, 4, 5, 12, 11, 4, 23, 66, 89, 99]
[-12, 4, 5, 11, 4, 12, 23, 66, 89, 99]
[-12, 4, 5, 4, 11, 12, 23, 66, 89, 99]
[-12, 4, 4, 5, 11, 12, 23, 66, 89, 99]
[-12, 4, 4, 5, 11, 12, 23, 66, 89, 99]
排序后:
[-12, 4, 4, 5, 11, 12, 23, 66, 89, 99]Process finished with exit code 0
二分查找法