我目前有这个代码执行Merge排序(尚未完成),我想知道是否有人知道如何在没有递归的情况下执行此操作。我坚持的部分是每次拆分后我必须继续创建新子阵列的部分。例如,如果我有一个长度为8的数组:
我需要2个数组用于初始拆分为4和4然后当我必须再次拆分为2 2 2 2时,这意味着我需要再增加4个数组..依此类推。如何在没有递归的情况下完成此任务?
到目前为止,我在代码中进行了第一次拆分:
void merge_sort(int arr[], int len) // len = 10, array of 10
{
int i;
int *firsthalf;
int *secondhalf;
int firsthalf_elements, secondhalf_elements;
if (len<2)
{
return;
}
firsthalf_elements = len/2;
secondhalf_elements = len - firsthalf_elements;
firsthalf = (int*)malloc(sizeof(int) * n1);
secondhalf = (int*)malloc(sizeof(int) * n2);
for (i =0; i < firsthalf_elements; i++)
{
firsthalf[i] = arr[i];
}
for (i = 0; i < secondhalf_elements; i++)
{
secondhalf[i] = arr[i+firsthalf_elements];
}
//Normally over here we would make a recursive call, but i want to do this w/o recursion.
答案 0 :(得分:-2)
这是无需递归即可实现合并排序的方法。
#include<stdio.h>
#include<cstdlib>
#include<time.h>
#define n 10//Size of array
void mergesort(int *,int);
void merge(int *,int,int,int);
int min(int,int);
int main()
{
int i;
int * arr;
srand(time(NULL));
arr = (int *)malloc(sizeof(int) * n);
for(i = 0; i < n; ++i)
arr[i] = rand()%100;
printf(" Array before sorting is \n");
for(i=0;i<n;i++)
printf(" %d ",arr[i] );
printf("\n Array after sorting is \n");
mergesort(arr,n);
for(i=0;i<n;i++)
printf(" %d ",arr[i] );
return 0;
}
void mergesort(int *arr,int m)
{
int size;
int index;
for(size=1;size<m-1;size=size*2)
{
for(index=0;index<m-1;index=index+size*2)
{
int middle=index+size-1;
int endindex=min(index+2*size-1,m-1);
merge(arr,index,middle,endindex);
}
}
}
void merge(int *arr,int start,int middle,int end)
{
int size=end-start+1;
int temp[n];
int i=start;
int j=middle+1;
int k=start;
while((i<=middle)&&(j<=end))
{
if(arr[i]<=arr[j])
{
temp[k]=arr[i];
i++;
}
else if (arr[i]>arr[j])
{
temp[k]=arr[j];
j++;
}
k++;
}
if(i>middle)
{
while(j<=end)
{
temp[k]=arr[j];
j++;
k++;
}
}
if(j>end)
{
while(i<=middle)
{
temp[k]=arr[i];
i++;
k++;
}
}
for(i=start;i<k;i++)
arr[i]=temp[i];
}
int min(int a,int b)
{
if(a<=b)
return a;
else
return b;
}
有关更多详细信息,请访问- https://github.com/SahdevKansal02/Data-Structures-And-Algorithms.git