冒泡排序
算法负责度为O(n^2)
@Test
public void bubbleMin() {
int[] numsInt = {1, 0, -2, 9, 8};
logger.info("原始数据: {}", numsInt);
for (int index = 0; index < numsInt.length - 1; index++) {
for (int jndex = numsInt.length - 1; jndex > index; jndex--) {
if (numsInt[jndex] < numsInt[jndex - 1]) {
// 临近比较:遍历将最小放在前面
int tmp = numsInt[jndex];
numsInt[jndex] = numsInt[jndex - 1];
numsInt[jndex - 1] = tmp;
}
}
logger.info("{}: {}", index, numsInt);
}
}
print:
2019-05-31 12:05:04-[INFO ]-[main:0 ]-[com.cscs.RegexTest:156:(0)]-原始数据: [1, 0, -2, 9, 8]
2019-05-31 12:05:04-[INFO ]-[main:0 ]-[com.cscs.RegexTest:166:(0)]-0: [-2, 1, 0, 8, 9]
2019-05-31 12:05:04-[INFO ]-[main:0 ]-[com.cscs.RegexTest:166:(0)]-1: [-2, 0, 1, 8, 9]
2019-05-31 12:05:04-[INFO ]-[main:0 ]-[com.cscs.RegexTest:166:(0)]-2: [-2, 0, 1, 8, 9]
2019-05-31 12:05:04-[INFO ]-[main:0 ]-[com.cscs.RegexTest:166:(0)]-3: [-2, 0, 1, 8, 9]
@Test
public void bubbleMax() {
int[] numsInt = {1, 0, -2, 9, 8};
logger.info("原始数据: {}", numsInt);
for (int index = numsInt.length - 1; index >= 0 ; index--) {
for (int jndex = 0; jndex < index; jndex++) {
if (numsInt[jndex] > numsInt[jndex + 1]) {
// 临近比较:遍历将最大放在后面
int tmp = numsInt[jndex];
numsInt[jndex] = numsInt[jndex + 1];
numsInt[jndex + 1] = tmp;
}
}
logger.info("{}: {}", index, numsInt);
}
}
2019-05-31 12:11:29-[INFO ]-[main:0 ]-[com.cscs.RegexTest:173:(0)]-原始数据: [1, 0, -2, 9, 8]
2019-05-31 12:11:29-[INFO ]-[main:0 ]-[com.cscs.RegexTest:183:(0)]-4: [0, -2, 1, 8, 9]
2019-05-31 12:11:29-[INFO ]-[main:0 ]-[com.cscs.RegexTest:183:(0)]-3: [-2, 0, 1, 8, 9]
2019-05-31 12:11:29-[INFO ]-[main:0 ]-[com.cscs.RegexTest:183:(0)]-2: [-2, 0, 1, 8, 9]
2019-05-31 12:11:29-[INFO ]-[main:0 ]-[com.cscs.RegexTest:183:(0)]-1: [-2, 0, 1, 8, 9]
2019-05-31 12:11:29-[INFO ]-[main:0 ]-[com.cscs.RegexTest:183:(0)]-0: [-2, 0, 1, 8, 9]
插入排序
@Test
public void insert() {
// 利用list插入特性
int[] numsInt = {1, 0, -2, 9, 8};
List<Integer> numsList = new ArrayList<>();
logger.info("原始数据: {}", numsInt);
numsList.add(numsInt[0]);
for (int index = 1; index < numsInt.length; index++) {
for (int jndex = 0; jndex < numsList.size(); ++jndex) {
if (numsList.get(jndex) > numsInt[index]) {
// 找到比自身大的位置插入
numsList.add(jndex, numsInt[index]);
break;
}
if (jndex == numsList.size() - 1) {
// 尾部插入
numsList.add(numsList.size(), numsInt[index]);
break;
}
}
logger.info("{}: {}", index, numsList);
}
}
2019-05-31 16:23:48-[INFO ]-[main:0 ]-[com.cscs.RegexTest:192:(0)]-原始数据: [1, 0, -2, 9, 8]
2019-05-31 16:23:48-[INFO ]-[main:0 ]-[com.cscs.RegexTest:206:(0)]-1: [0, 1]
2019-05-31 16:23:48-[INFO ]-[main:0 ]-[com.cscs.RegexTest:206:(0)]-2: [-2, 0, 1]
2019-05-31 16:23:48-[INFO ]-[main:0 ]-[com.cscs.RegexTest:206:(0)]-3: [-2, 0, 1, 9]
2019-05-31 16:23:48-[INFO ]-[main:0 ]-[com.cscs.RegexTest:206:(0)]-4: [-2, 0, 1, 8, 9]