package com.iamitman.sort;
import java.util.Arrays;
/**
* 冒泡排序:
* 从下至上每两个相邻的值进行比较,若满足要求,则交换两个值位置
* 增加交换判断标识swap,若存在某一轮循环中,没有交换即顺序已经排好,不用去做后面多余的比较了
*
* @param <T>
*/
public class BubbleSort<T extends Comparable> {
/**
* 从小到大
*
* @param t
* @return
*/
public T[] sort(T[] t) {
int length = t.length;
boolean swap = true;
for (int i = 0; i < length && swap; i++) {
swap = false;
for (int j = length - 1; j > i; j--) {
if (t[j].compareTo(t[j - 1]) < 0) {
T temp = t[j - 1];
t[j - 1] = t[j];
t[j] = temp;
swap = true;
}
}
}
return t;
}
public static void main(String[] args) {
BubbleSort sort = new BubbleSort();
Integer[] example = {6, 4, 2, 3, 5, 1, 7, 10, 8, 9};
System.out.println(Arrays.toString(sort.sort(example)));
}
}