我正在努力进行合并排序工作,我一直试图自己调试问题,但我无法看到它。我可以使用一些帮助。 正如我所说的,我有一个合并排序,它给了我完全随机的数字。我相信它是因为我尝试通过2个函数传输的数组参数,但我不确定。
编辑:所以我发现了2个错误
首先,我在通过数组部分时没有增加i
while(lim1<=mid && lim2<=end)
{
if(*(a+lim1)<=*(a+lim2))
{
*(aux+i)=*(a+lim1);
lim1++;
}
else
{
*(aux+i)=*(a+lim2);
lim2++;
}
i++;
}
第二个是我添加随机值,因为辅助数组比它应该更大(起初我认为它不重要) 由此改变:
int s=end-start;
int aux[s];/*So I wil only have
the required value
without any random values
*/
但我仍然得到错误的价值观,不过没有更多的randoms,现在似乎重复了这些价值观。 Edit2:更改了我的2个函数的名称。
编辑3:填空代码
/*
Program description: Program that sorts an array using merge sort
Author: Andrei Negura
Date: 12/07/2017
Os: win 10
*/
#include <stdio.h>
#include <stdlib.h>
#define START 0
#define SIZE 10
void sort(int *, int, int);
void merge(int *, int, int, int);
void read(int *);
void display(int *);
int main()
{
int array[ SIZE ];
read( array );
display( array );
printf("\n");
merge( array, START, SIZE-1);
display( array );
return 0;
}
void read(int *a)
{
int i;
printf("Enter %d elements\n", SIZE);
for(i= START; i< SIZE; i++)
scanf("%d", &*(a+i) );
}
void display(int *a)
{
int i;
printf("\nElements\n");
for( i= START; i< SIZE; i++)
printf("%d ", *(a+i) );
}
/*
Function that divides the array into subarrays
Divide and conquer method
Recursive function
*/
void sort(int *a, int start, int end)
{
int mid;
if( start< end)
{
mid= ( start + end) / 2;
merge( a, start, mid);
merge( a, mid+1, end);
sort( a, start, mid, end);
}
}
/*
Function that actually sorts the elements
lim1 and lim2 will act as index values,
that's why Idon't use the parameters
The parameters will be my limits(until
what point lim1 and lim2 go)
Auxiliary Array to store the sorted array
*/
void merge(int *a, int start, int mid, int end)
{
int s= end - start;
int aux[s];//So I wil only have \
the required value \
without any random values
int i=0;
int lim1= start, lim2= mid+1;
/*
The I does not reset, If i reset i,
I lose the count for the auxiliary array
*/
/*
Go through both parts of the array at once
until one of them is finished
*/
while(lim1 <= mid && lim2 <= end)
{
if( *( a + lim1 ) <= *( a + lim2 ) )
{
*( aux + i ) = *( a + lim1 );
lim1++;
}
else
{
*( aux + i ) = *( a + lim2 );
lim2++;
}
i++;
}
//Go through first part, if not finished already
while( lim1 <= mid)
{
*( aux + i ) = *( a + lim1 );
i++;
lim1++;
}
//Go through second part, if not finished already
while( lim2 <= end)
{
*( aux + i )= *( a + lim2);
i++;
lim2++;
}
//Rewrite the sorted array back into a
for( i = START; i <= s; i++)
*( a + i )= *( aux + i );
}