您的位置:首页 > 其它

改进的冒泡排序

2015-10-26 15:24 211 查看
用一个标记来记录上次交换的最后一个位置,位置后面的序列就是有序的了。有序的就不用再排了,节省了时间,提高了效率。

head.h

#define MAXSIZE 100
typedef int KeyType;
typedef int InfoType;
typedef struct{
	KeyType key;
	InfoType otherinfo;
}RedType;
typedef struct{
	RedType r[MAXSIZE+1];
	int length;
}SqList;
void GBubbletSort(SqList &L);
void ShowList(SqList &L);


function.cpp

#include"head.h"
#include<iostream>
using namespace std;
void GBubbletSort(SqList &L)
{
	RedType chan;
	int lastswap=L.length-1;
	int flag=L.length-1;
	for(int i=0;i<L.length;i++)
	{
		lastswap=flag;
		for(int j=0;j<lastswap;j++)
		{
			if(L.r[j].key>L.r[j+1].key)
			{
				chan=L.r[j];
				L.r[j]=L.r[j+1];
				L.r[j+1]=chan;
				flag=j;
			}
		}
		if(flag==lastswap)
				break;
	}
}
void ShowList(SqList &L)
{
	if(L.r==NULL)
	{
		cout<<"the array is not exist!"<<endl;
		exit(0);
	}
	for(int i=0;i<L.length;i++)
		cout<<L.r[i].key<<"  ";
	cout<<endl;
}


main.cpp

#include"head.h"
#include<iostream>
using namespace std;
void main()
{
	cout<<"请输入数组长度length:";
	int length;
	cin>>length;
	cout<<"请输入"<<length<<"个数:"<<endl;
	SqList arr;
	arr.length=0;
	for(int i=0;i<length;i++)
	{
		cin>>arr.r[i].key;
		arr.length++;
	}
	GBubbletSort(arr);
	cout<<"冒泡排序后的数组:"<<endl;
	ShowList(arr);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: