#include<stdlib.h>
#include<stdio.h>
using namespace std;
void swap(int* a,int* b)
{
int tmp = *a;
*a = *b;
*b = tmp;
}
void Bubble_Sort(int* arry, int count)//O(n*n)
{
int i = 0;
int j = 0;
for ( i = 0; i < count; i++)//n
{
for ( j = count-1; j > i; j--)//n
{
if (arry[j]<arry[j-1])
{
swap(&arry[j], &arry[j - 1]);
/*int tmp = arry[j];
arry[j] = arry[j - 1];
arry[j - 1] = tmp;*/
}
}
}
}
//优化的冒泡排序
void Bubble_Sort1(int* arry, int count)
{
int i = 0;
int j = 0;
int exchange = 1;
for (i = 0; i < count; i++)
{
exchange = 0;
for (j = count - 1; j > i; j--)
{
if (arry[j]<arry[j - 1])
{
swap(&arry[j], &arry[j - 1]);
exchange = 1;
/*int tmp = arry[j];
arry[j] = arry[j - 1];
arry[j - 1] = tmp;*/
}
}
}
}
void main()
{
int arry[] = { 12,20,45,25,35,1,2,54,52 };
int count = sizeof(arry) / sizeof(*arry);
printf("arry数组个数:%d\n", count);
for (int i = 0; i < count; i++)
{
printf("%d ", arry[i]);
}
printf("\n排序之前");
Bubble_Sort1(arry, count);
for (int i = 0; i < count; i++)
{
printf("%d ", arry[i]);
}
printf("\n排序之后");
system("pause");
}
排序算法-冒泡排序
最新推荐文章于 2022-09-06 20:12:26 发布