#define OK 1
#define ERROR 0
#define OVERFLOW -2
#define MAXSIZE 100
#include
using namespace std;
SqList L;
Status InitList_Sq(SqList &L){ //构造一个空的顺序表L
L.r= new ElemType[MAXSIZE]; //为顺序表分配空间
if (!L.r) exit(OVERFLOW); //存储分配失败
L.length = 0; //空表长度为0
return OK;
}
Status add(SqList &L, int i)
{
int j, a;
cout << "请输入数值:" << endl;
for (j = 1; j < i; j++)
{
++L.length;
cin >> a;
L.r[j].key = a;
}
return OK;
}
void InsertSort(SqList &L)
{
int i, j;
for (i = 2; i <= L.length; ++i)
if (L.r[i].key
L.r[0] = L.r[i]; // 复制为哨兵
L.r[i] = L.r[i - 1];
for (j = i - 2; L.r[0].key
L.r[j + 1] = L.r[0]; //插入到正确位置
}
}
void bubble_sort(SqList &L)
{
int m,t, i, j, flag = 1;
m = L.length - 1;
while ((m>0) && (flag == 1))
{
flag = 0;
for (j = 1; j <= m; j++)
if (L.r[j].key>L.r[j + 1].key)
{
flag = 1;
t = L.r[j].key; L.r[j].key = L.r[j + 1].key; L.r[j + 1].key = t; //交换
}//endif
m--;
}//endwhile
}
int Partition(SqList &L,int low,int high)
{
int pivotkey;
L.r[0].key = L.r[low].key; pivotkey = L.r[low].key;
while (low < high)
{
while (low < high && L.r[high].key >= pivotkey) --high;
L.r[low].key = L.r[high].key;
while (low < high && L.r[low].key <= pivotkey) ++low;
L.r[high].key = L.r[low].key;
}
L.r[low].key = L.r[0].key;
return low;
}
void Qsort(SqList &L,int low , int high){
int p;
if (low
p = Partition(L, low, high);
Qsort(L, low,p-1);
Qsort(L, p+1, high);
}
}
void SelectSort(SqList &L)
{
int i,k,j,t;
for (i = 1; i
k = i;
for (j = i + 1; j <= L.length; j++)
if (L.r[j].key
{
t = L.r[i].key; L.r[i] = L.r[k]; L.r[k].key = t;
}
}
}
Status List(SqList &L)
{
int i, a;
for (i = 1; i < L.length + 1; i++) //空出数组的首位
{
a = L.r[i].key;
cout << a << "\t";
}
return 0;
}
int main()
{
int ch, i, a, b, x;
do
{
cout << endl;
cout << "1.初始化-InitList" << endl;
cout << "2.添加数据-Add" << endl;
cout << "3.显示- List" << endl;
cout << "4.直接插入排序" << endl;
cout << "5.冒泡排序" << endl;
cout << "6.快速排序" << endl;
cout << "7.直接选择排序" << endl;
printf("请输入你的选择:");
cin >> ch;
switch (ch)
{
case 1:InitList_Sq(L); break;
case 2:add(L,8); break;
case 3:List(L); break;
case 4:InsertSort(L); break;
case 5:bubble_sort(L); break;
case 6:Qsort(L, 1, L.length); break;
case 7:SelectSort(L); break;
default:
break;
}
} while (1);
}