赞
踩
#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); }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。