6-7 歸併排序(遞迴法) (10分)_資料結構實驗8_羊卓的楊
阿新 • • 發佈:2020-12-19
6-7 歸併排序(遞迴法) (10分)
本題要求實現二路歸併排序中的歸併操作,待排序列的長度1<=n<=1000。
函式介面定義:
void Merge(SqList L,int low,int m,int high);
其中L是待排序表,使排序後的資料從小到大排列。
裁判測試程式樣例:
#include <iostream>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 1000
using namespace std;
typedef int ElemType;
typedef struct
{
ElemType *r;
int length;
}SqList;
void Create_Sq(SqList &L);//建立待排序列,實現細節隱藏
void Merge(SqList L,int low,int m,int high);
void MSort(SqList L,int low,int high)
{ /*用分治法進行二路歸併排序*/
int mid;
if(low<high){/*區間長度大於1*/
mid= (low+high)/2; /*分解*/
MSort(L,low,mid); /*遞迴地對low到mid序列排序 */
MSort(L,mid+1,high); /*遞迴地對mid+1到high序列排序 */
Merge(L,low,mid,high);/*歸併*/
}
}
int main()
{
SqList L;
int i;
L.r=new ElemType[MAXSIZE+1];
L.length=0;
Create_Sq(L);
MSort(L,1,L.length);
for(i=1;i<=L.length;i++)
if (i==1) cout<<L.r[i];
else cout<<" "<<L.r[i];
return 0;
}
/* 請在這裡填寫答案 */
輸入樣例:
第一行輸入關鍵字個數(輸入的值不大於 MAXSIZE),接下來輸入n個關鍵字。
7
24 53 45 45 12 24 90
輸出樣例:
輸出由小到大的有序序列,每一個關鍵字之間由空格隔開。
12 24 24 45 45 53 90
答案樣例
int b[1001];
void Merge(SqList L,int low,int m,int high) {
int p1=low, p2=m+1;
for(int i=low; i<=high; i++) {
if((p1<=m) && ((p2>high) || (L.r[p1]<L.r[p2]))) {
b[i] = L.r[p1++];
} else {
b[i] = L.r[p2++];
}
}
for(int i=low; i<=high; i++)
L.r[i] = b[i];
}
感謝您的閱讀,點個贊吧❤⭐
嗶哩嗶哩/bilibili:羊卓的楊
公眾號:羊卓的楊