寫一個程序完成以下功能:
(1) 一條記錄有學號和成績兩個數據項,依次輸入數據(學號,成績): (5,60),(6,80),(7,76),(8,50),建立一個順序表,並寫一個插入函數,把以上數據寫到主函數中依次調用插入函數。要求:先輸入的數據排在前面,不要按學號或成績從大到小排序。
(2) 依次輸出表中所有數據。
(3) 寫一個函數對表中所有數據按照成績從大到小進行排序。
(4) 再次輸出所有數據。
(5) 建立另外一個順序表,依次輸入數據:(10,70),(20,85),(30,75), (40,90),並且按照(3)寫好的函數對該順序表進行排序。
(6) 寫一個函數合並以上兩個有序表,使得合並之后的表是有序的(從大到小)。即實現函數 merge(SqList *A, SqList *B, SqList *C),把A,B兩個有序表合並在表C中去。並且最好不用二重循環實現算法,也不用重新調用排序函數。
#include "stdio.h" #define MAXSIZE 100 typedef struct { int NO; int score; }ElemType; typedef struct { ElemType elem[MAXSIZE]; int length; }SqList; //初始化 void InitList(SqList *pL) { pL->length =0; } //插入 void InsertList(SqList *pL,ElemType e,int i) { if(pL->length >MAXSIZE) return; pL->elem [i]=e; pL->length ++; } //排序 void SortScore(SqList *pL) { for(int i=0;i<pL->length ;i++) for(int j=i+1;j<pL->length ;j++) { if(pL->elem [i].score<pL->elem [j].score ) { ElemType temp=pL->elem [i]; pL->elem [i]=pL->elem [j]; pL->elem [j]=temp; } } } void Merge(SqList *pL,SqList *pS,SqList *T) { int i=0,j=0,k=0; while(i<pL->length &&j<pS->length ) { if(pL->elem [i].score >pS->elem [j].score ) T->elem [k++]=pL->elem [i++]; else T->elem [k++]=pS->elem [j++]; } while(i<pL->length ) T->elem [k ++]=pL->elem [i++ ]; while(j<pS->length ) T->elem [k ++]=pS->elem [j ++]; } //輸出 void Printf(SqList *pL) { for(int i=0;i<pL->length ;i++) printf("(%2d,%2d)\n",pL->elem [i].NO ,pL->elem [i].score ); } void main() { SqList L,S,T; ElemType e; InitList(&L); e.NO =5; e.score =60; InsertList(&L,e,0); e.NO =6; e.score =80; InsertList(&L,e,1); e.NO =7; e.score =76; InsertList(&L,e,2); e.NO =8; e.score =50; InsertList(&L,e,3); printf("順序表L:\n"); Printf(&L); printf("\n按照成績大小排序后的順序表L:\n"); SortScore(&L); Printf(&L); InitList(&S); e.NO =10; e.score =70; InsertList(&S,e,0); e.NO =20; e.score =85; InsertList(&S,e,1); e.NO =30; e.score =75; InsertList(&S,e,2); e.NO =40; e.score =90; InsertList(&S,e,3); printf("\n順序表S:\n"); Printf(&S); printf("\n按照成績大小排序后的順序表S:\n"); SortScore(&S); Printf(&S); printf("\n\n"); InitList(&T); T.length =L.length +S.length ; Merge(&L,&S,&T); Printf(&T); }