我正在尝试实现合并排序算法。我正在遵循 CLRS 书中提到的算法。这是我的代码
#include<stdio.h>
#include<stdlib.h>
void merge_sort(int *arr,int start_index,int end_index);
void merge(int *arr,int start_index,int middle_index,int end_index);
int main(){
int arr[]={5,2,1,6,0,3,3,4}; //8 elements last index 7
int i;
printf("Before sorting.\n");
for(i=0;i<8;i++)
printf("%d",arr[i]);
merge_sort(arr,0,7);
printf("\nAfter sorting.\n");
for(i=0;i<8;i++)
printf("%d",arr[i]);
return 0;}
void merge_sort(int *arr,int start_index,int end_index){
int middle_index;
if(start_index<end_index)
{
middle_index=(start_index+end_index)/2;
merge_sort(arr,start_index,middle_index);
merge_sort(arr,(middle_index+1),end_index);
merge(arr,start_index,middle_index,end_index);
}
}
void merge(int *arr, int start_index,int middle_index, int end_index){
int n1,n2,i,l,m;
n1=middle_index-start_index+2;
n2=end_index-middle_index+1;
int sub_arr1[n1],sub_arr2[n2];
for(i=0;i<(n1-1);i++)
sub_arr1[i]=arr[i];
for(i=0;i<(n2-1);i++)
sub_arr2[i]=arr[middle_index+1+i];
sub_arr1[n1+1]=100;
sub_arr2[n2+1]=100;
for(i=0;i<=end_index;i++){
l=0,m=0;
if(sub_arr1[l]<sub_arr2[m])
{arr[i]=sub_arr1[l++];}
else
{arr[i]=sub_arr2[m++];}
}}
我得到以下输出
Before sorting.
52160334
After sorting.
22222222
RUN FINISHED; exit value 0; real time: 10ms; user: 0ms; system: 0ms
因为我取小整数,所以我取 100 作为sentinel value
. 我想合并功能有问题。任何帮助表示赞赏。