冒泡算法逻辑比较简单,就是遍历一遍,相邻两个值比较,然后往前移动一次。
/**
* @Author: 张
* @Date: 2019/1/30 08:27
* @Version: 1.0
* @Description: 1.0
*/
public class BubblingSortTest {
public static int[] bubblingSort(int[] array) {
if (array == null || array.length == 0)
return array;
final int[] arr = array.clone();
for (int index = 0; index < arr.length; index++) {
for (int innerIndex = 0; innerIndex < arr.length - index - 1; innerIndex++) {
if (arr[innerIndex] > arr[innerIndex + 1]) {
swap(arr, innerIndex, innerIndex + 1);
}
}
}
return arr;
}
public static void swap(int[] arr, int i, int j) {
int ai = arr[i];
arr[i] = arr[j];
arr[j] = ai;
}
public static void main(String[] args) {
int[] array = new int[]{1, 2, 0, 4, 9, 6, 5, 3};
int[] array1 = bubblingSort(array);
for (int ar : array1) {
System.out.print(ar + ",");
}
}
}