1.冒泡排序(优化前+优化后)
//优化前
static void bubble(int a[]) {
int temp;
for (int i = 0; i < a.length - 1; i++) {
for (int j = 0; j < a.length - 1 - i; j++) { //第一趟排序
if (a[j] >= a[j + 1]) {
temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
}
}
}
}
//优化后
static void bubble_greater(int a[]) {
int temp;
boolean flag = false;
for (int i = 0; i < a.length - 1; i++) {
for (int j = 0; j < a.length - 1 - i; j++) { //第一趟排序
if (a[j] >= a[j + 1]) {
flag = true;
temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
}
}
if (flag == false) { //说明一次也没有交换过 ,已经排序完成,后续不用再排序
break;
} else {
flag = false;
}
}
}
2.选择排序(优化前+优化后)
//优化前排序
static void select(int a[]) {
for (int j = 0; j < a.length - 1; j++) {
for (int i = 1 + j; i < a.length; i++) {
int temp;
if (a[j] > a[i]) {
temp = a[j];
a[j] = a[i];
a[i] = temp;
}
}
}
}
//优化后的选择排序
static void select_greater(int a[]) {
for (int i = 0; i < a.length - 1; i++) {
int minIndex = i;
int min = a[i];
for (int j = 1 + i; j < a.length; j++) {
if (min > a[j]) {
min = a[j];
minIndex = j;
}
}
if (i != minIndex) {
a[minIndex] = a[i];
a[i] = min;
}
}
}
3.插入排序
static void insert(int a[]) {
int insertValue = 0; //待插入数据 将定义放在外面较好 减少少许开销
int insertIndex = 0; //待插入数据的下标
for (int i = 1; i < a.length; i++) {
insertValue = a[i];
insertIndex = i -1;
while (insertIndex >= 0 && insertValue < a[insertIndex]){ //判断条件
a[insertIndex + 1] = a[insertIndex]; //满足条件,向后移动
insertIndex--;
}
if (insertIndex != i){
a[insertIndex + 1] =insertValue; //位置插入
}
}
}