简体   繁体   中英

Merge Sort With Specific Arguments

I am supposed to write the merge sort function and merge function with the given arguments. However, my code does not print anything. I believe it goes into an endless recursive loop. I believe my logic is right. Any advice on where I went wrong would be appreciated.

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

void merge(int* A, int n, int mid){
  int *temp = (int*)malloc(sizeof(int)*n);
  //set indexes for left and right side of array and 
  //the beginning of the temporary array
  int array_index = 0; //temporary array
  int left = 0; //left side
  int right = mid;

  while(left < mid && right < n){
    if(A[left] < A[right]){
      temp[array_index] = A[left];
      left++;
      array_index++;
    }else if(A[right] < A[left]){
      temp[array_index] = A[right];
      right++;
      array_index++;
    }
  }
   while(left < mid){
    temp[array_index] = A[left];
    left++;
    array_index++;
  }
  while(right< mid){
    temp[array_index] = A[right];
    right++;
    array_index++;
  }
 for(int i = 0; i<n; i++){
    A[i] = temp[i];
  }
  free(temp);
}

void merge_sort(int *A, int n){
    if(n>=2){
    int mid = n/2;
    merge_sort(A,mid);
    merge_sort(A+mid,n-mid);
    merge(A, n, mid);
  }
}

int main(void) {
  int arr[10] = {1,5,3,13,88,21,55,23,99,1};
  merge_sort(arr, 10);
  for(int i = 0; i<10; i++){
    printf("%d ",arr[i]);
  }
  return 0;
}

if(A[left] < A[right]){ should be if(A[left] <= A[right]){ and remove if(A[right] < A[left]) from corresponding else clause

also

while(right< mid){ should be while(right< n){

Corrected code at Ideone gives 1 1 3 5 13 21 23 55 88 99

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM