1. 程式人生 > >順序表上實現氣泡排序及其優化

順序表上實現氣泡排序及其優化

氣泡排序

1)定義順序表的儲存結構;

2)在順序表上實現氣泡排序;

3)將普通的氣泡排序進行多次改進以提高排序速度,並用大量資料測試其速度的提高。

1.普通版:

2.第一步優化:

若在一次排序中沒有發生交換,說明此時已經全部有序無需再進行掃描
增加一個標記,記錄是否進行過交換

3.第二步優化:

若上次排序位置為end,表示end-n的數已經有序,下次排序不需要再遍歷

#include <iostream>
#include <stdlib.h>
#include <stdio.h>
using namespace std;

//定義順序表的儲存結構;
typedef struct {
	int key;//關鍵字項
	int otherinfo;//其他資料元素
}RedType;
typedef struct {
	RedType r[105];//r[0]閒置或用作哨兵單元
	int length;//順序表表長
}SqList;//順序表型別


void CreatSq(SqList &L) {
	printf("請輸入資料個數:");
	scanf("%d", &L.length);
	printf("請輸入%d個數據元素:", L.length);
	for (int i = 1; i <= L.length; i++)
		scanf("%d", &L.r[i].key);
}
void Print(SqList L) {
	printf("升序輸出:");
	for (int i = 1; i <= L.length; i++)
		printf("%d ", L.r[i].key);
	printf("\n\n");
}

//(2)在順序表上實現氣泡排序;
void BubbleSort_A(SqList &L) {
	CreatSq(L);
	for (int i = 1; i<L.length; i++) {
		for (int j = 2; j <= L.length; j++) {
			if (L.r[j - 1].key>L.r[j].key) {
				swap(L.r[j - 1].key, L.r[j].key);
			}
		}
	}
	Print(L);
}

//冒泡法第一步優化
//若在一次排序中沒有發生交換,說明此時已經全部有序無需再進行掃描
//增加一個標記,記錄是否進行過交換
void BubbleSort_B(SqList &L) {
	CreatSq(L);
	bool flag;//標記是否進行了排序
	for (int i = 1; i<L.length; i++) {
		flag = false;
		for (int j = 2; j <= L.length; j++) {
			if (L.r[j-1].key>L.r[j].key) {
				swap(L.r[j-1].key, L.r[j].key);
				flag = true;
			}
		}
		if (!flag) break;//若沒有排序,序列有序,退出
	}
	Print(L);
}

//若上次排序位置為end,表示end-n的數已經有序,下次排序不需要再遍歷
void BubbleSort_C(SqList &L) {
	CreatSq(L);
	bool flag = true;
	int end = L.length;
	int k = end;
	for (int i = 1; i<L.length; i++) {
		flag = false;
		for (int j = 2; j <= end; j++) {
			if (L.r[j - 1].key>L.r[j].key) {
				swap(L.r[j - 1].key, L.r[j].key);
				flag = true;
				k = j;
			}
		}
		end = k;
		if (!flag) break;
	}
	Print(L);
}
int main()
{
	SqList L;
	printf("1.普通氣泡排序\n");
	BubbleSort_A(L);
	printf("2.第一步優化後氣泡排序\n");
	BubbleSort_B(L);
	printf("3.第二步優化後氣泡排序\n");
	BubbleSort_C(L);
	system("pause");
	return 0;
}