排序算法之--冒泡排序

冒泡排序的C++实现代码如下所示:

该冒泡排序的时间复杂度为O(n^2),当将要排序的序列本身是排好的时候,该时间复杂度则为O(n)。

// Sort.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <iostream>
#include <string>

using namespace std;

template <typename T>
void Bubble(T Array[], T length)
{
	if (Array == NULL || length < 0)
	{
		return;
	}

	for (int j = 0; j < length; j++)
	{
		for (int i = 0; i < length-j-1; i++)// 因为是i+1, 所以防止越界length - 1,  
		{
			if (Array[i] > Array[i+1])
			{
				T tmp = Array[i];
				Array[i] = Array[i+1];
				Array[i+1] = tmp;
			}
		}// end for i
		
		//length--; // 等价于length - j

	}// end for j
}


int _tmain(int argc, _TCHAR* argv[])
{
	cout << "Please intput data for bubble sort!" << endl;
	cout << "Length : ";
	int length = 0;
	cin >> length;
	
	if (0 == length)
	{
		cerr << "Check out the input length and input again!" << endl;
		cin >> length;
	}

	cout << "Data : ";

	int InData = 0;
	int *Array = new int[length * sizeof(int *)];// 分配内存空间

	for (int i = 0; i < length; i++)
	{
		cin >> InData;
		Array[i] = InData;
	}

	cout << "Raw input data : " << endl;
	for (int i = 0; i < length; i++)
	{		
		cout << Array[i] << endl;
	}
	

	Bubble<int>(Array,length);

	cout << "Bubble sort reslut : " << endl;
	for (int k = 0; k < length; k++)
	{			
		cout << Array[k] << endl;
	}

	delete []Array;

	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Digital2Slave

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值