程序代码:
#include"stdio.h"
#include"stdlib.h"
#include<iostream>
using namespace std;
void swap(int &a, int &b)
{
int c;
c = a;
a = b;
b = c;
}
void bubble_sort(int a[], int n)
{
printf("the unsort data is:");//打印数据未排序的结果
for (int i = 0; i < n; i++)
printf("%d ", a[i]);
cout << endl;
int i, j;
for (i = 0; i < n - 1; i++)
{
for (j = 0; j < n-1-i; j++)
{
if (a[j]>a[j + 1])
swap(a[j], a[j + 1]);
}
printf("the %dth sort data is:",i+1);//打印数据每次排序后的结果
for (int i = 0; i < n; i++)
printf("%d ", a[i]);
cout << endl;
}
printf("the sort data is:");//打印排序后的结果
for (int i = 0; i < n; i++)
printf("%d ", a[i]);
cout << endl;
}
int main()
{
int a[10] = { 2, 5, 8, 7, 9, 10, 3, 1, 4, 6 };
bubble_sort(a, 10);
system("pause");
return 0;
}
实验结果: