# C中的合并排序算法无法正常工作

``````#include <stdio.h>
#include <stdlib.h>

// Function to Merge Arrays L and R into A
// leftCount = number of elements in L
// rightCount = number of elements in R

void Merge(int *A,int *L,int leftCount, int *R, int rightCount)
{

// i, to mark the index of subarray (L)
// j, to mark the index of subarray (R)
// k, to mark the index of subarray (A)

int i = 0;
int j = 0;
int k = 0;

while(i<leftCount && j<rightCount)
{
if(L[i] <= R[j])
{
A[k++] = L[i++];
}
else
{
A[k++] = R[j++];
}
}
while(i<leftCount)
{
A[k++] = L[i++];
}
while(j<rightCount)
{
A[k++] = R[j++];
}
}

// Recursive function to sort an array of integers

void MergeSort(int *A, int n)
{
int i;
int mid;
int *L;
int *R;
if (n<2) // Base condition
{
return;
}

mid = n/2; // Find the mid index
L = (int*)malloc(mid*sizeof(int));
R = (int*)malloc((n-mid)*sizeof(int));

for(i=0;i<mid;i++) // Creating left subarray
{
L[i] = A[i];
}
for(i=mid;i<n;i++) // Creating right subarray
{
R[i-mid] = A[i];
}

MergeSort(L,mid);
MergeSort(R,n-mid);
Merge(A,L,R,mid,n-mid);
free(L);
free(R);
}

int main()
{

int A[] = {2,4,1,6,8,5,3,7};
int i;
int numberofelements;
numberofelements = sizeof(A)/sizeof(A[0]);
MergeSort(A,8);

for(int i = 0; i<8; i++)
{
printf("%d ",A[i]);
return 0;
}
}
``````

``````void Merge(int *A,int *L,int leftCount, int *R, int rightCount)
``````

``````Merge(A,L,R,mid,n-mid);
``````

0 条评论