DS之順序表實現亂序輸入順序輸出,ds
順序表的執行個體有很多,在學其他的程式設計語言時,肯定都學過要求輸入一串亂序的數字,要求進行排序,實現升序或降序輸出。今天就來用順序表實現亂序輸入,順序輸出(升序)。
實現上述的功能需要用到的順序表的基本操作有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 10typedef 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;//長度為0L.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
輸出的結果為: