稳定性:
假定在待排序的记录序列中,存在多个具有相同的关键字的记录,若经过排序,这些记录的相对次序保持不变,即在原序列中,r[i]=r[j],且r[i]在r[j]之前,而在排序后的序列中,r[i]仍在r[j]之前,则称这种排序算法是稳定的;否则称为不稳定的。即存在相等的数据,它们的相对顺序不会发生改变。
package sortalgorithm.bubblesort;
import com.alibaba.fastjson.JSON;
import java.util.Arrays;
import java.util.List;
/**
* @author whale_fall
* @Description 冒泡排序
* @date 2022/11/13
*/
public class BubbleSort {
/**
* 冒泡排序
* 描述:依次比较两个数,较大的数往后移动,
* 每次排序后都可以找到一个相对大的数放在最后,所以每次排序后后面的是有序的
* 时间复杂度为:平均时间复杂度:O(n^2);最好的情况:O(n)
* 空间复杂度为:O(1)
* 是否是稳定的:是
*
* @param args
*/
public static void main(String[] args) {
List<Integer> tempList = Arrays.asList(new Integer[]{3, 44, 38, 5, 47, 15, 36, 26, 27, 2, 46, 4, 19, 50, 48});
bubbleSort1(tempList);
bubbleSort2(tempList, tempList.size());
System.out.println(JSON.toJSONString(tempList));
}
private static void bubbleSort1(List<Integer> tempList) {
int len = tempList.size();
for (int j = 0; j < len; j++) {
for (int i = 0; i < len -j- 1; i++) {
int curr = tempList.get(i);
int next = tempList.get(i + 1);
if (curr > next) {
tempList.set(i + 1, curr);
tempList.set(i, next);
}
}
}
System.out.println(JSON.toJSONString(tempList));
}
private static void bubbleSort2(List<Integer> tempList, int len) {
if (len < 2) return;
for (int i = 0; i < len - 1; i++) {
int curr = tempList.get(i);
int next = tempList.get(i + 1);
if (curr > next) {
tempList.set(i + 1, curr);
tempList.set(i, next);
}
}
bubbleSort2(tempList, len - 1);
}
}