排序之冒泡排序(C++)

终于到了“大话数据结构”最后一个章节了。当然前面的图和树还有待大量的学习和训练。

冒泡排序,应该是最简单的排序方式了,以下为其基本和改进实现:

Input number (q to quite): 5 3 1 9 4 6 3 7 9 1 6 4 3 4 q
Your input List is: 5 3 1 9 4 6 3 7 9 1 6 4 3 4
After bubble sort: 1 1 3 3 3 4 4 4 5 6 6 7 9 9
#include<iostream>

using namespace std;

#define MAXSIZE 100

struct List
{
	int data[MAXSIZE];
	int size;
};

void swap(List &L, int i, int j)
{
	int temp = L.data[i];
	L.data[i] = L.data[j];
	L.data[j] = temp;
}

void show(const List &L)
{
	for (int i = 0; i < L.size; i++)
		cout << L.data[i] << " ";
	cout << endl;
}

void BubbleSort(List &L)
{
	for (int i = 0; i < L.size-1; i++) {
		for (int j = 0; j < L.size - i -1; j++) {
			if (L.data[j] > L.data[j+1])
				swap(L, j, j+1);
		}
	}
}

void BubbleSort2(List &L)
{
	bool flag = true;
	for (int i = 0; i < L.size - 1&&flag; i++) {
		flag = false;
		for (int j = 0; j < L.size - i - 1; j++) {
			if (L.data[j] > L.data[j + 1]) {
				swap(L, j, j + 1);
				flag = true;
			}
		}
	}
}

void main()
{
	List test;
	cout << "Input number (q to quite): ";
	int temp;
	test.size = 0;
	while (test.size <= MAXSIZE&&cin >> temp) {
		test.data[test.size] = temp;
		test.size += 1;
		cout << "Input number (q to quite): ";
	}
	cin.clear();
	cin.ignore(100, '\n');
	cout << "Your input List is: ";
	show(test);
	cout << "After bubble sort: ";
	BubbleSort2(test);
	show(test);
}

改进方法“BubbleSort2”,是为了优化当列表中已经是具有一定序列的情况,可以去掉已排好序的冗余判断过程。冒泡排序的时间复杂度是:
  O ( n 2 ) \ O(n^2)  O(n2)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值