#include<stdio.h>
#include<iostream>
#include<algorithm>
using namespace std;
//打印数组元素
void printArray(int array[],int size)
{
for(int i=0; i<size; i++)
{
cout<<array[i]<<" ";
}
cout<<" "<<endl;
}
void bubble_sort(int array[],int size)
{
int count_start=1; //内部循环计数
int count_end=1; //外部循环计数
for(int i=1; i<size; i++) //进行n-1次 控制选择气泡的次数
{
for(int j=size-1; j>=i; j--) //从下往上,依次比较相邻元素
{
if(array[j]<array[j-1]) //将气泡小的往上浮
{
swap(array[j], array[j-1]);//交换两个数
}
//这些只是方面代码的理解,可以删除下面两句
cout<<"第"<<count_start++<<"次--内部--上升的过程"<<endl;
printArray(array, size);
}
//这些只是方面代码的理解,可以删除下面
count_start=1;
cout<<" "<<endl;
cout<<"-------第"<<count_end++<<"最终的排序结果(外部-----即每一次内部的最终排序结果)--------"<<endl;
cout<<" "<<endl;
printArray(array, size);
cout<<"-------第"<<count_end--<<"次结束!--------"<<endl;
cout<<"-------END--------"<<endl;
cout<<" "<<endl;
}
}
int main()
{
int array[]= {49,38,65,97,76,13,27,49,10};
int size = sizeof(array)/sizeof(int); //获取数组的长度
//print length
cout<<"the array's length is:"<<size<<endl;
printArray(array,size);
cout<<"the program is:"<<" " <<endl;
cout<<"-------START--------"<<endl;
bubble_sort(array,size);
}
冒泡排序---基础版本--c++(考研)
最新推荐文章于 2024-04-21 12:45:57 发布