冒泡排序

排序思想:

冒泡排序是最常见的一种排序方法,某种意义上来说,也是最土的一种。

基本过程是这样的:

假设一无序队列,需要从小排列到大。依次比较两个相邻的值,选择是否交换,保证小值在左,大值在右,这样第一轮过去最大值就在最右边了。

然后第二轮还是从第一个值开始遍历,但是这一次只需交换只需要跑到倒数第二个值,因为最后一个值已经做定了。

以此类推。。


它与选择排序的区别是:(假设从小排到大)

选择排序每次找的是最小值,冒泡每次找的是最大值。然后再排剩下的值。


代码如下:

// 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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值