2020-03-19 02:40

# 请大神帮我看看 这归并排序哪里写错了

5

#include
#include
#include
//归并排序 先划分 分别排序 然后归并
int helper[100];

void merger(int*a,int p,int mid,int r)
{

``````memcpy(helper,a,sizeof(int)*(r-p+1));

int left=p;//左侧队伍头部指针，指向带比较的元素
int right=mid+1;//右侧
int current=p;//原数组指针，指向代填入数据的位置;
while(left<=mid&&right<=r)
{
if(helper[left]<=helper[right])
{ a[current]=helper[left];
current++;
left++;
}else{
a[current]=helper[left];
current++;
right++;
}
}
while(left<=mid)
{
a[current]=helper[left];
current++;
left++;
}
``````

}
void mergersort(int*a,int p,int r)
{
if(p<r)
{
int mid=(p+r)/2;
mergersort(a,p,mid);
for(int i=0;i<3;i++)

``````    mergersort(a,mid+1,r);
for(int i=3;i<6;i++)

merger(a,p,mid,r);
}
``````

}
main()
{
int a[]={1,3,5,7,9,2};
mergersort(a,0,5);
for(int i=0;i<6;i++)
printf("%d",a[i]);
}

• 点赞
• 写回答
• 关注问题
• 收藏
• 复制链接分享
• 邀请回答

#### 1条回答

• 回答这么多问题就耍赖把我的积分一笔勾销了 1年前
``````#include<stdlib.h>
#include<string.h>
#include<stdio.h>
//归并排序 先划分 分别排序 然后归并
int helper[100];
void merger(int arr[], int left, int mid, int right, int *temp){
int i = left;
int j = mid + 1;
int k = left;
while (i <= mid&&j <= right){
if (arr[i] < arr[j]){
temp[k++] = arr[i++];
}
else{
temp[k++] = arr[j++];
}
}
while (i <= mid){
temp[k++] = arr[i++];
}
while (j <= right){
temp[k++] = arr[j++];
}
memcpy(arr + left, temp + left, sizeof(int)*(right - left+1));
}
void mergesort(int arr[],int left,int right,int *temp){
int mid = 0;
if (left < right){
mid = left + (right - left) / 2;
mergesort(arr, left, mid, temp);
mergesort(arr, mid + 1, right, temp);
merger(arr, left, mid, right, temp);
}
}
int main()
{
int a[]={1,3,5,7,9,2};
mergesort(a,0,5,helper);
for(int i=0;i<6;i++)
printf("%d ",a[i]);
}

``````
点赞 1 评论 复制链接分享