c中最难掌握的是指针,其余的都比较简单的...
小晕乎
在这给大家分享一个一个问题希望大家能帮我解决一下,我编了一个归并排序在tc2.0中通过但是在vc中总是出问题检测数据:310,285,179,652,351,423,861,254,450,520共10个.一下是详细代码:
#include<iostream.h>
#include<stdio.h>
#include<malloc.h>
void merge(int *a,int low,int mid,int high)
{
int *b;
int l,m,h;
int i,j,k;
l=low;
h=high;
m=(l+h)/2;
i=low;
j=mid+1;
/*b=new int[h-l+1];*/
b=(int *)malloc((h-l+1)*sizeof(int));
while(i<=m&&j<=h)
{
if(a[i]<=a[j])
{
b[l]=a[i];
i++;
l++;
}
else
{
b[l]=a[j];
j++;
l++;
}
}
if(i<=m)
{
while(i<=m)
{
b[l]=a[i];
l++;i++;
}
}
if(j<=h)
{
while(j<=h)
{
b[l]=a[j];
l++;j++;
}
}
for(k=low;k<=high;k++)
a[k]=b[k];
/*delete []b;*/
free(b);
}
void mergesort(int *a,int low,int high)
{
int mid;
if(low<high)
{
mid=(low+high)/2;
mergesort(a,low,mid);
mergesort(a,mid+1,high);
merge(a,low,mid,high);
}
}
void main()
{
int *a;
int i,n,l,h;
/*cout<<"intput the number of elements:n=";*/
printf("intput the number of elements:n=");
/*cin>>n;*/
scanf("%d",&n);
/*a=new int[n+1];*/
a=(int *)malloc((n+1)*sizeof(int));
/*cout<<"intput the elements:\n";*/
printf("input the elements:\n");
for(i=0;i<n;i++)
/*cin>>a[i];*/
scanf("%d",&a[i]);
l=0;
h=n;
mergesort(a,l,h);
/*cout<<"\nthe result is:\n";*/
printf("\nthe result is:\n");
for(i=0;i<n;i++)
/*cout<<a[i]<<" ";*/
printf("%d ",a[i]);
/*cout<<endl;*/
printf("\n");
return ;
}