冒泡排序是什么?我们先来看百度百科的介绍
java代码实现
public class BubbleSoft {
public static void main(String[] args) throws IOException {
// 定义一个数组用来测试
int[] arr = {
1, 23, 5, 4, 6, 66, 35, 33, 52, 444, 99, 1, 36, 55, 77, 63};
System.out.println("排序前:");
show(arr);
bubbleSoft(arr);
System.out.println("排序后:");
show(arr);
}
/**
* 普通排序
* @param arr
*/
public static void bubbleSort1(int[] arr) {
if (null == arr) {
return;
}
for (int i = 0; i < arr.length; i++) {
for (int j = i + 1; j < arr.length; j++) {
if (arr[i] > arr[j]) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
}
/**
* 增强后
* @param arr
*/
public static void bubbleSoft(int[] arr) {
// 获取数组元素个数
int n = arr.length;
// 只有一个元素,不需要排序
if (n <= 1) {
return;
}
// 记录比较次数
int sum = 0;
// 设置falg为false,用于判定是否进行了元素交换
boolean falg = false;
// 进行n次比较
for (int j = 0; j < n; j++) {
for (int i = 0; i < n - j - 1; i++) {
// 每经过一次排序,最大的元素都会有序的调到最后面
// 已经排序了的元素不需要再进行比较,只需要对前 n-j-1 进行比较
sum++;
if (arr[i] > arr[i + 1]) {
// 当前元素比后一个元素大,进行交换
int temp = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = temp;
falg = true;
}
}
if (!falg) {
break;
} else {
falg = false;
}
}
System.out.printf("本次排序比较了%d次\n", sum);
}
// 定义方法用于打印数组元素
public static void show(int[] arr) {
for (int i : arr) {
System.out.print(i + "\t");
}
System.out.println();
}
}
/**
* 选择排序 ,每次都找出最小元素的下标,与第i次循环的下标元素进行交换
* @param arr
*/
public static void selectSort(int[] arr) {
for (int i = 0; i < arr.length - 1; i++) {
int minIndex = i;
for (int j = i + 1; j < arr.length; j++) {
if (arr[minIndex] > arr[j]) {
minIndex = j;
}
}
if (i != minIndex) {
// 需要交换
int temp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = temp;
}
}
}
public static void insertSort(int[] arr){
for (int i = 0; i < arr.length - 1; i++) {
for (int j = i + 1; j > 0; j--) {
// 内部是来交换数据的
if (arr[j - 1] < arr[j]) {
int temp = arr[j-1];
arr[j-1] = arr[j];
arr[j] = temp;
} else {
// 到此前面数组已经是全部有序的 不需要再交换 退出循环
break;
}
}
}
}