冒泡排序

1.优点:比较简单,空间复杂度较低,是稳定的;

2.缺点:时间复杂度太高,效率慢;

1
2
3
4
5
6
7
8
9
10
int[] arr = new int[]{12, 3, 13, 15, 10, 2, 9, 3, 17};
for (int i = 0; i < arr.length; i++) {
for (int n = 0; n < arr.length; n++) {
if (arr[n] > arr[i]) {
int temp = arr[i];
arr[i] = arr[n];
arr[n] = temp;
}
}
}

选择排序

1.优点:一轮比较只需要换一次位置;

2.缺点:效率慢,不稳定;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
int[] arr = new int[]{12, 3, 13, 15, 10, 2, 9, 3, 17};
for (int i = 0; i < arr.length; i++) {
//记录最小值下标
int minIndex = i;
for (int n = i + 1; n < arr.length; n++) {
//比较并替换最小值下标
if (arr[n] < arr[minIndex]) {
minIndex = n;
}
}
//交换值
if (minIndex != i) {
int temp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = temp;
}

}