博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
冒泡排序
阅读量:2504 次
发布时间:2019-05-11

本文共 1434 字,大约阅读时间需要 4 分钟。

排序思想:

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

基本过程是这样的:

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

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

以此类推。。

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

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

代码如下:

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

转载地址:http://bmlgb.baihongyu.com/

你可能感兴趣的文章
datatable columns与columnDefs
查看>>
提交 git 项目 到 github 在 centos 7
查看>>
linux, configure --prefix 的作用
查看>>
C# 类相同属性赋值
查看>>
新的一天
查看>>
js限制input标签中只能输入中文
查看>>
laravel中及其常用的一些函数方法(自己看)和技巧(不断添加中)
查看>>
编程十年 (8):歪打正着C#
查看>>
.Net程序员 初学Ubuntu ,配置Nignix
查看>>
一个段错误调试
查看>>
Codeforces-936B Sleepy Game
查看>>
kubernetes系列
查看>>
exports和module.exports的区别
查看>>
Memcached add 命令
查看>>
ansible简要说明
查看>>
Unity of Prism
查看>>
原型模式和享元模式
查看>>
Day 16:输入输出字符流、缓冲输入字符流
查看>>
hiho一下 第200周 题目1 : Shortening Sequence
查看>>
分析AppClassLoader,ExtClassLoader 和URLClassLoader 的关系
查看>>