冒泡排序(Bubble Sort)
冒泡排序:典型的比较排序
package org.study.order;
import java.util.Arrays;
public class BubbleSort01 {
public static void main(String[] args) {
int[] arr = {91, 23, 103, 44, 25, 78, 1};
int[] last = bubbleSort(arr);
System.out.println(Arrays.toString(last));
}
public static int[] bubbleSort(int[] arr) {
for(int end = arr.length; end > 0; end --) {
for (int begin = 0; begin < end - 1; begin ++) {
if (compare(arr[begin], arr[begin + 1]) < 0){ //相等的情况不需要交换,尽量保持为稳定的排序
swap(begin, begin + 1, arr);
} else {
continue;
}
}
}
return arr;
}
public static int compare(int pre, int post) {
if (pre > post) {
return -1;
} else {
return 1;
}
}
public static int[] swap(int indexA, int indexB, int[] arr) {
int tmp = arr[indexA];
arr[indexA] = arr[indexB];
arr[indexB] = tmp;
return arr;
}
}
程序改变世界