前言
概述
冒泡排序这个算法 的思路比较简单,也较容易理解。
冒泡排序 (Bubble Sort )一种交换 排序,它的基本思想是:两两比较相邻记录的 关键字,如果反序则交换,直到没有反序的记录为止。冒泡的实现在细节上可以有很 多种变化,下面就用图示演示一下冒泡的过程。
排序,当然要有无序的数据啦,还是使用数据结构第一天(生成1000以内的随机数自动填充数组)中的代码生成我们需要的数据:
进行第一轮两两比较:
第一轮两两比较之后,开始第二轮两两比较:
。。。。。。
中间过程省略,按照上面的步骤循环,可以得到最终的结果:
源码:
void sortByBubbleSort(int* dest, const unsigned int dataCnt)
{
for (int i = 0; i < dataCnt-1; ++i)
{
for (int j = 0; j < dataCnt - 1; ++j)
{
if (*(dest + j)>*(dest + j + 1))
{
swap(*(dest + j),*(dest + j + 1));
}
}
}
}
主函数:
#include<stdio.h>
#include<iostream>
using namespace std;
#include"dataStructAPI.h"
#include"sort.h"
#include<windows.h>
int main()
{
int array[16] = { 0 };
numberProducer.getFilledArray(array,16);
cout << " 原 始 数 据 :";
numberProducer.showArray(array,16);
sortByBubbleSort(array, 16);
cout << "冒 泡 排 序 后 :";
numberProducer.showArray(array, 16);
sortByShellInsert(array, 16, 5);
cout << "希尔插入排序后 :";
numberProducer.showArray(array, 16);
sortByBinarySearchInsert(array, 16);
cout << "折半插入排序后 :";
numberProducer.showArray(array, 16);
sortByDirectInsert(array, 16);
cout << "直接插入排序后 :";
numberProducer.showArray(array, 16);
system("pause");
return 0;
}