merge sort: looping variables test condition

merge
sort

#1

there is a for loop at the end of the function merge() wherin i<=num_elements is used. why is it <= and not just i< num_elements

#include<stdio.h>

void m_sort(int numbers[], int temp[], int left, int right);
void mergeSort(int numbers[], int temp[], int array_size);
void merge(int numbers[], int temp[], int left, int mid, int right);

void mergeSort(int numbers[], int temp[], int array_size)
{
  m_sort(numbers, temp, 0, array_size - 1);
}
 
 
void m_sort(int numbers[], int temp[], int left, int right)
{
  int mid;
 
  if (right > left)
  {
    mid = (right + left) / 2;
    m_sort(numbers, temp, left, mid);//this calls for sorting the left part
    m_sort(numbers, temp, mid+1, right);//this calls for sorting the right part,mid+1 because mid goes to the left half in the previous statement
 
    merge(numbers, temp, left, mid+1, right);//why mid+1
  }
}
 
void merge(int numbers[], int temp[], int left, int mid, int right)//left middle and right of the array or left half or right half
{
  int i, left_end, num_elements, tmp_pos;//num_elts for no._elts of array,l_e is middle postion,tmp_pos keeps track of the position of elt filling
                                         //in the temporary array,i is used in for loop that comes in the end
  left_end = mid - 1;//left end means the end of the left end
  tmp_pos = left;//tmp pos is the postion of the place being filled in the temporary array
  num_elements = right - left + 1;
 
  while ((left <= left_end) && (mid <= right))//compares the first elts of the two halfs and fills it into temp array
  {
    if (numbers <= numbers[mid])
    {
      temp[tmp_pos] = numbers;
      tmp_pos = tmp_pos + 1;
      left = left +1;
    }
    else
    {
      temp[tmp_pos] = numbers[mid];
      tmp_pos = tmp_pos + 1;
      mid = mid + 1;
    }
  }
 
  while (left <= left_end)//if right half used up fills the remaining slots in the temp array with the elts left in left half
  {
    temp[tmp_pos] = numbers;
    left = left + 1;
    tmp_pos = tmp_pos + 1;
  }
  while (mid <= right)//same as above while loop only thing is here the operation done on the other side
  {
    temp[tmp_pos] = numbers[mid];
    mid = mid + 1;
    tmp_pos = tmp_pos + 1;
  }
 
  for (i=0; i <= num_elements; i++)//copies the values from temp array to number array
  {
    numbers[right] = temp[right];
    right = right - 1;
  }
}

int main(void)
{
 int size;
 printf("enter the size of the array

“);
scanf(”%d",&size);
int a[size],t[size];

 printf("enter the elements

");

 for(int i=0;i<size;i++)
  {
   scanf("%d",&a*);
   
  }
  
  mergeSort(a,t,size);
  
  for(int i=0;i<size;i++)
   printf("%d ",a*); 
  return 0;
}

#2

You can go through the below links…i would suggest that you see one of the youtube tutorials!!!

http://faculty.simpson.edu/lydia.sinapova/www/cmsc250/LN250_Weiss/L15-MergeSort.htm