排序思想:
冒泡排序是最常见的一种排序方法,某种意义上来说,也是最土的一种。
基本过程是这样的:
假设一无序队列,需要从小排列到大。依次比较两个相邻的值,选择是否交换,保证小值在左,大值在右,这样第一轮过去最大值就在最右边了。
然后第二轮还是从第一个值开始遍历,但是这一次只需交换只需要跑到倒数第二个值,因为最后一个值已经做定了。
以此类推。。
它与选择排序的区别是:(假设从小排到大)
选择排序每次找的是最小值,冒泡每次找的是最大值。然后再排剩下的值。
代码如下:
// ConsoleApplication4.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "windows.h"
#include "time.h"
const int N = 10;
int O = 0;
int* GenRandom()
{
srand( (unsigned)time( NULL ) );
int* a = new int[N];
for (int i = 0; i < N; i++)
{
a[i] = rand() * rand();
}
return a;
}
void swap(int& a, int& b)
{
int temp = 0;
temp = a;
a = b;
b = temp;
}
//small -> large
void BubbleSort(int* ua)
{
O = 0;
//round times
for (int i = 0; i < N; i++)
{
printf("round %d \r\n", i);
for (int i = 0; i < N; i++)
{
printf("a[%d]=%d \r\n",i, *(ua+i));
}
for (int j = 0; j < (N-i-1); j++)
{
if(ua[j] > ua[j+1])
{
swap(ua[j], ua[j+1] );
}
O++;
}
}
}
SYSTEMTIME StartTime = {0};
FILETIME StartFileTime = {0};
SYSTEMTIME EndTime= {0};
FILETIME SEndFileTime= {0};
int* a = 0;
int _tmain(int argc, _TCHAR* argv[])
{
a = GenRandom();
//BubbleSort-----------------
GetSystemTime(&StartTime);
printf("timeBefore %d:%d:%d \r\n", StartTime.wMinute, StartTime.wSecond, StartTime.wMilliseconds);
printf("BubbleSort\r\n");
BubbleSort(a);
GetSystemTime(&EndTime);
printf("timeAfter %d:%d:%d \r\n", EndTime.wMinute, EndTime.wSecond, EndTime.wMilliseconds);
printf("times %d \r\n", O);
return 0;
}
6385

被折叠的 条评论
为什么被折叠?



