# 八大排序算法-冒泡排序

## 代码

#include<stdio.h>
#include<stdlib.h>

//常规冒泡排序
void bubbleSort(int r[],int n){

int i,j;
int temp;
for(i=0;i<n;i++){
for(j=n-1;j>i;j--){
if(r[j]<r[j-1]){
temp = r[j];
r[j] = r[j-1];
r[j-1] = temp;
}
}
}
}

//改进后的冒泡排序,添加一个flag
void bubble_1(int r[],int n){
int i,j,temp;
bool flag = true;
for(i=0;i<n;i++){
flag = false;
for(j=n-1;j>i;j--){
if(r[j]<r[j-1]){
temp = r[j];
r[j] = r[j-1];
r[j-1] = temp;
flag = true;
}
}
}
}

//改进后的冒泡排序，双向查找
void bubble_2(int r[],int n){
int temp,i;
int low = 0;
int high = n-1;
while(low<high){
for(i=low;i<high;i++){//正向冒泡,找到最大值者
if(r[i]>r[i+1]){
temp = r[i];
r[i] = r[i+1];
r[i+1] = temp;
}
}
high--; //修改high前移一位
for(i=high;i>low;i--){//反向冒泡,找到最小者
if(r[i]<r[i-1]){
temp = r[i];
r[i] = r[i-1];
r[i-1] = temp;
}
}
low++; //修改low后移一位
}
}
//打印
void print(int r[],int n){
int i=0;
for(i=0;i<n;i++){
printf("%3d",r[i]);
}
printf("\n");
}

int main(){
int r[] = {3,5,2,8,7,9,6,4,1,0},r1[10],r2[10];
int i;

for(i=0;i<10;i++){
r1[i] = r[i]*3;//初始化r1，r2数组
r2[i] = r[i]*2;
}
printf("r排序前：\n");
print(r,10);
printf("常规冒泡排序：\n");
bubbleSort(r,10);//常规冒泡
print(r,10);

printf("\nr1排序前:\n");
print(r1,10);
printf("添加了flag的冒泡排序：\n");
bubble_1(r1,10);//添加flag
print(r1,10);

printf("\nr2排序前:\n");
print(r2,10);
printf("双向查找的冒泡排序：\n");
bubble_2(r2,10); //双向查找
print(r2,10);
printf("\n");
printf("\n");

}