合并排序的实现不起作用?
Implementation of merge sort not working?
运行代码后我的数组没有排序。怎么了?
结果:3,8,9,6,11,3,22,95。
我试了很久都没有用。
int main(int argc, char const *argv[]){
int i;
int my[]={3,11,19,22,8,9,13,95};
msort(my,0,7);
for(i=0;i<8;i++){
printf("%d,",my[i]);
}
return 0;
}
int msort(int *ar,int low, int high){
int mid;
if(low<high){
mid = (low+high)/2;
msort(ar,low,mid);
msort(ar,mid+1,high);
merge(ar,low,mid,high);
}
}
int merge(int *ar,int low,int mid, int high){
//int ar[]={3,11,19,22};
//int ar2[]={8,9,13,95};
int temp[8];
int i,j,index,k;
k=0;
index=low;
i=low;
j=mid+1;
while(i<=mid && j<=high){
if(ar[i]<ar[j]){
temp[index++] = ar[i];
i++;
}else{
temp[index++] = ar[j];
j++;
}
}
while(i<j){
temp[index++] = ar[i];
i++;
}
while(j<i){
temp[index++] = ar[j];
j++;
}
//here i am updating my array with temp;
for(k=low;k<high;k++){
ar[k]=temp[k];
}
}
您的 while 条件已关闭,需要清空数组 while (j<i)
永远不会为真。
while (i <= mid) {
temp[index++] = ar[i];
i++;
}
while (j <= high) {
temp[index++] = ar[j];
j++;
}
int merge(int *ar,int low,int mid, int high){
int temp[8];
int i,j,index,k;
k=0;
index=0;//temp's index start 0;
i=low;
j=mid+1;
while(i<=mid && j<=high){
if(ar[i]<ar[j]){
temp[index++] = ar[i];
i++;
}else{
temp[index++] = ar[j];
j++;
}
}
while(i<=mid){
temp[index++] = ar[i];
i++;
}
while(j<=high){
temp[index++] = ar[j];
j++;
}
for(k=low, index=0;k<=high;k++){//k include high
ar[k]=temp[index++];
}
}
运行代码后我的数组没有排序。怎么了?
结果:3,8,9,6,11,3,22,95。
我试了很久都没有用。
int main(int argc, char const *argv[]){
int i;
int my[]={3,11,19,22,8,9,13,95};
msort(my,0,7);
for(i=0;i<8;i++){
printf("%d,",my[i]);
}
return 0;
}
int msort(int *ar,int low, int high){
int mid;
if(low<high){
mid = (low+high)/2;
msort(ar,low,mid);
msort(ar,mid+1,high);
merge(ar,low,mid,high);
}
}
int merge(int *ar,int low,int mid, int high){
//int ar[]={3,11,19,22};
//int ar2[]={8,9,13,95};
int temp[8];
int i,j,index,k;
k=0;
index=low;
i=low;
j=mid+1;
while(i<=mid && j<=high){
if(ar[i]<ar[j]){
temp[index++] = ar[i];
i++;
}else{
temp[index++] = ar[j];
j++;
}
}
while(i<j){
temp[index++] = ar[i];
i++;
}
while(j<i){
temp[index++] = ar[j];
j++;
}
//here i am updating my array with temp;
for(k=low;k<high;k++){
ar[k]=temp[k];
}
}
您的 while 条件已关闭,需要清空数组 while (j<i)
永远不会为真。
while (i <= mid) {
temp[index++] = ar[i];
i++;
}
while (j <= high) {
temp[index++] = ar[j];
j++;
}
int merge(int *ar,int low,int mid, int high){
int temp[8];
int i,j,index,k;
k=0;
index=0;//temp's index start 0;
i=low;
j=mid+1;
while(i<=mid && j<=high){
if(ar[i]<ar[j]){
temp[index++] = ar[i];
i++;
}else{
temp[index++] = ar[j];
j++;
}
}
while(i<=mid){
temp[index++] = ar[i];
i++;
}
while(j<=high){
temp[index++] = ar[j];
j++;
}
for(k=low, index=0;k<=high;k++){//k include high
ar[k]=temp[index++];
}
}