起泡排序——交换排序

/**
* Copyright (C) 2015, CSU
* All rights reserved
* File Name:test.cpp
* Author: lmm
* Date of completion: 2015/1/20
* Version: v1.0
*
* 问题描述:起泡排序
* 输入描述: 输入整数
* 知识点  : 内部排序
* 程序输出: 输出有序整数
*/

#include <iostream>
#include <stdio.h>
#include <math.h>
using namespace std;
//起泡排序一
void BubbleInsert_One(int *seqList,int length)
{
	int temp = 0;
	for (int i = 0; i < length; ++i)   // 比较的趟数
	{
		for (int j = 1; j < length-i; ++j) // 每一趟都会将一个最大记录沉入底部
		{
			if (seqList[j] < seqList[j-1] )
			{
				int temp = seqList[j];
				seqList[j] = seqList[j-1];
				seqList[j-1] = temp;
			}
		}
	}
}
//起泡排序二
void BubbleInsert_Two(int *seqList,int length)
{
	int bound,exchange = length-1;
	while(exchange != 0)
	{
		bound = exchange;
		exchange = 0;	// 每次将exchange清零
		for (int i = 0; i < bound; i++)
		{
			if (seqList[i] > seqList[i+1])
			{
				int temp = seqList[i];
				seqList[i] = seqList[i+1];
				seqList[i+1] = temp;
				exchange = i;				// 记录交换的边界
			}
		}
	}

}
int main()
{
	int a[10] = {0};
	int seqNum = 0;
	cout << "Input ten numbers: ";
	for (int i = 0; i < 10; ++i)  // 输入10个数,result[0]为哨兵
	{
		cin >> seqNum;
		a[i] = seqNum;
	}
	BubbleInsert_One(a,10);
	//BubbleInsert_Two(a,10);
	cout << endl << "Output the results: ";
	for (int j = 0; j < 10; ++j)
	{
		cout << a[j] << " ";
	}
	cout << endl;
	return 0;

}

总结:

      若初始序列为“正序”序列,则只需进行一趟排序,在排序过程中进行n-1次关键字间的比较,且不移动记录。

  若初始序列为“逆序”序列,则需进行n-1趟排序,需进行次比较,并作等数量级的记录移动。因此,总的时间复杂度为

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值