冒泡算法基础到进价篇
2020-02-23 本文已影响0人
easy_luo
1、基础冒泡
void ly_bubbleSort(int a[], int length){
for (int i = 0; i < length - 1; i++) {
for (int j = 0; j < length - i - 1; j++) {
if (a[j] > a[j+1]) {
int temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
}
}
2、基础优化
void ly_bubbleSort1(int a[], int length){
BOOL isSort = YES;
for (int i = 0; i < length - 1; i++) {
for (int j = 0; j < length - i - 1; j++) {
if (a[j] > a[j+1]) {
int temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
isSort = NO;
}
}
if (isSort) {
break;
}
}
}
3、冒泡终极进价
void ly_bubbleSort2(int a[], int length){
BOOL isSort = YES;//默认数组已经排好序
int index = 0;
for (int i = 0; i < length - 1; i++) {
int maxLen = length - i - 1;
for (int j = index; j < maxLen; j++) {//将最大值往后挪动
if (a[j] > a[j+1]) {
int temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
isSort = NO;
}
}
if (isSort) {//如果数组已经排好序,直接返回
break;
}
isSort = YES;//默认数组已经排好序
for (int j = maxLen; j > index; j--) {//将最小值往前挪动
if (a[j] > a[j-1]) {
int temp = a[j];
a[j] = a[j-1];
a[j-1] = temp;
isSort = NO;
}
}
if (isSort) {//如果数组已经排好序,直接返回
break;
}
index++;//将最小值往前挪动,又进行了一次冒泡,起始位置要加1
}
}