gpt4 book ai didi

c - 修改合并排序以存储原始索引

转载 作者:太空宇宙 更新时间:2023-11-04 02:52:10 26 4
gpt4 key购买 nike

<分区>

我尝试修改合并排序以存储原始索引,修改后排序不正确。我找不到哪里出错了请帮我找到问题。

请在下面找到我的代码。

void merge(int a[][2],int start,int middle ,int end)
{
int size1 = middle-start +1;
int size2 = end-middle;
int i,j;
int k =start;
int L[size1][2];
int R[size2][2];
//int *L = (int *)malloc(sizeof(int)*size1);
//int *R = (int *)malloc(sizeof(int)*size2);

// copy values from main array to temp arrays
for(i=0 ; i<size1; i++)
{
L[i][1] = a[i+start][1];
L[i][0] = a[i+start][0];
}
for(j=0 ; j<size2 ; j++)
{
R[j][1] = a[j+middle+1][1];
R[j][0] = a[j+middle+1][0];
}

i=0;
j=0;
while(i<size1 && j<size2)
{
if(L[i] < R[j])
{
a[k][1] = L[i][1];
a[k][0] = L[i][0];
k++;
i++;
}
else{
a[k][1] = R[j][1];
a[k][0] = R[j][0];
k++;
j++;
}
}
while(i<size1)
{
a[k][1] = L[i][1];
a[k][0] = L[i][0];
i++;
k++;
}
while(j<size2)
{
a[k][1] = R[j][1];
a[k][0] = R[j][0];
k++;
j++;
}
}

void mergeSort(int a[][2], int start , int end)
{
if(start < end)
{
int middle = start + (end - start) /2;
mergeSort(a,start, middle);
mergeSort(a,middle+1,end);
merge(a,start,middle,end);
}
}

int main()
{
int array[10][2] = {{0,55},{1,3},{2,4},{3,5},{4,6},{5,7},{6,8},{7,9},{8,10},{9,2}};
int i;
int len = sizeof(array)/sizeof(array[0]) - 1;
for(i = 0 ;i <= 9; i++)
printf("%d",array[i][1]);
mergeSort(array,0,9);
printf ( "\nArray after sorting:\n") ;
printf ( "\nindex after sorting:\n") ;
for(i = 0 ;i <= 9; i++)
printf("%d",array[i][0]);
printf ( "\nArray after sorting:\n") ;
for(i = 0 ;i <= 9; i++)
printf("%d",array[i][1]);
}

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com