顺序表的各种排序

#include<iostream>
using namespace std;
#define MAXSIZE 100

typedef int ElemType;
typedef struct{
	ElemType *elem;
	int length;
}SqList;
//初始化
bool InitList(SqList &L)
{
	L.elem = new ElemType[MAXSIZE];
	if(!L.elem) return false;
	L.length = 0;
	return true;
 } 
 //键盘键入值创建顺序表
void InsertData(SqList &L,int n)
{
	//n为要插入值的个数
	cout<<"请以此输入你要插入的值:"<<endl; 
	for(int i = 1;i<n+1;i++)
	{
		cin>>L.elem[i];
		L.length++;	
	}
	
} 
//show顺序表的内容
void ShowData(SqList L)
{
	for(int i = 1;i<L.length+1;i++)
		cout<<L.elem[i]<<" ";
	cout<<endl;
} 
//直接插入排序
void InsertSort(SqList L) 
{
	int j;
	for(int i=2;i<=L.length;++i)
	{
		if(L.elem[i]<L.elem[i-1])
		{
			L.elem[0] = L.elem[i];
			L.elem[i] = L.elem[i-1];
			for(j = i-2;L.elem[0]<L.elem[j];--j)
				L.elem[j+1] = L.elem[j];
			L.elem[j+1] = L.elem[0];
		}
	}
	cout<<"直接插入排序后的顺序表的内容是:"<<endl;
	ShowData(L); 
}
//折半插入排序
void BInsertSort(SqList L)
{
	int i,j,m,low,high;
	for(i=2;i<=L.length;++i)
	{
		L.elem[0] = L.elem[i];
		low = 1;
		high = i-1;
		while(low<=high)
		{
			m = (low+high)/2;
			if(L.elem[0]<L.elem[m]) high = m-1;
			else low = m+1;
		}
		for(j = i-1;j>=high+1;--j)
			L.elem[j+1] = L.elem[j];
		L.elem[high+1] = L.elem[0];
	}
	cout<<"折半插入排序后的顺序表的内容是:"<<endl;
	ShowData(L); 
 } 
 //冒泡排序
 void BubbleSort(SqList L)
 {
 	for (int i = 0; i < L.length ; i++) {
        for (int j = 1; j < L.length - i ; j++) 
		{   
            if (L.elem[j] >L.elem[j + 1]) {
                int temp = L.elem[j];
                L.elem[j] = L.elem[j + 1];
                L.elem[j + 1] = temp;
                }
            }
        }
	cout<<"冒泡排序后的顺序表的内容是:"<<endl;
	ShowData(L); 
  } 
//快速排序
int Partition(SqList &L,int low,int high)
{
	L.elem[0] = L.elem[low];
	int pivotkey = L.elem[low];
	while(low<high)
	{
		while(low<high&&L.elem[high]>=pivotkey) --high;
		L.elem[low] = L.elem[high];
		while(low<high&&L.elem[low]<=pivotkey) ++low;
		L.elem[high] = L.elem[low];
	}
	L.elem[low] = L.elem[0];
	return low;
}
void QSort(SqList &L,int low,int high)
{
	if(low<high)
	{
		int pivotloc = Partition(L,low,high);
		QSort(L,low,pivotloc-1);
		QSort(L,pivotloc+1,high);
	}
}  
void QuickSort(SqList &L)
{
	QSort(L,1,L.length);
 } 
int main()
{
	SqList L;
	InitList(L);
	int inn;
	cout<<"请输入你要插入值的个数:\n";
	cin>>inn;
	InsertData(L,inn);
	cout<<"顺序表的内容是:\n";
	ShowData(L); 
	//直接插入排序
	//InsertSort(L); 
	//折半插入排序
	//BInsertSort(L); 
	//冒泡排序
	//BubbleSort(L); 
	//快速排序
	QuickSort(L);
	ShowData(L); 
} 
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值