顺序表的实例有很多,在学其他的编程语言时,肯定都学过要求输入一串乱序的数字,要求进行排序,实现升序或降序输出。今天就来用顺序表实现乱序输入,顺序输出(升序)。
实现上述的功能需要用到的顺序表的基本操作有0基本操作前的准备,1初始化顺序表,6向顺序表插入数据元素。
自己只需写一个排序的函数,排序函数的代码为:
<span style="font-size:18px;">//排序函数
void paixu(SqList &L)
{
for(int i=0;i<L.length;i++)
{
for(int j=0;j<L.length;j++)
{
if(L.elem[j]>L.elem[i])
{
int temp;
temp=L.elem[i];
L.elem[i]=L.elem[j];
L.elem[j]=temp;
}
}
}
}</span>
然后只需在主函数中定义一个顺序表,乱序输入一些数据元素,调用排序函数,然后遍历输出排序后的顺序表的所有数据元素。整个代码为:
<span style="font-size:18px;">#include <iostream>
using namespace std;
#include <malloc.h>
#include <stdlib.h>
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define OVERFLOW -2
#define LIST_INIT_SIZE 100
#define LISTINCREMENT 10
typedef int ElemType;
typedef int Status;
typedef struct
{
ElemType *elem;//存储空间基址
int length;//当前长度
int listsize;//当前分配的存储容量
}SqList;//定义了一个结构体类型,并命名为Sqlist
//1初始化顺序表
Status InitList(SqList &L)
{
L.elem=(ElemType *)malloc(LIST_INIT_SIZE*sizeof(ElemType));
if(!L.elem)
{
exit(OVERFLOW);
}
L.length=0;//长度为0
L.listsize=LIST_INIT_SIZE;
return OK;
}
//6向顺序表插入数据元素
Status ListInsert(SqList &L,int i, ElemType e)
{
if(i<1||i>L.length+1)
{
return ERROR;
}
if (L.length>=L.listsize)
{
ElemType *newbase=(ElemType *)realloc(L.elem,(L.listsize+LISTINCREMENT )*sizeof(ElemType));
if(!newbase)
{
exit(OVERFLOW);
}
L.elem=newbase;
L.listsize+=LISTINCREMENT;
}
ElemType *q=&(L.elem[i-1]);
ElemType *p;
for(p=&(L.elem[L.length-1]);p>=q;--p)
{
*(p+1)=*p;
}
*q=e;
++L.length;
return OK;
}
//排序函数
void paixu(SqList &L)
{
for(int i=0;i<L.length;i++)
{
for(int j=0;j<L.length;j++)
{
if(L.elem[j]>L.elem[i])
{
int temp;
temp=L.elem[i];
L.elem[i]=L.elem[j];
L.elem[j]=temp;
}
}
}
}
int main()
{
SqList La;
InitList(La);
cout<<"请输入La中数据的个数:";
int na;
ElemType e;
cin>>na;
for(int i=1;i<=na;i++)
{
cin>>e;
ListInsert(La,i,e);
}
paixu(La);
cout<<"排序后的La的数据元素为:"<<endl;
for(i=0;i<na;i++)
{
cout<<La.elem[i]<<",";
}
cout<<endl;
return 0;
}</span>
输入顺序表的元素个数为:10
乱序输入的数据元素为:3 2 7 9 0 1 4 8 6 5
输出的结果为: