/**
* 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趟排序,需进行次比较,并作等数量级的记录移动。因此,总的时间复杂度为