merge sort algorithm

 merge sort


void mergeSort(int arr[], int l, int r)
{
       if (l < r)
    {
        // Same as (l+r)/2, but avoids overflow for
        // large l and h
        int m = (l+r)/2;

        // Sort first and second halves
        mergeSort(arr, l, m);
        mergeSort(arr, m+1, r);

        merge(arr, l, m, r);
    }
}


void merge(int arr[], int l, int m, int r)
{ int i=l;
  int j=m+1;
  int k=0;
  
  int temp[r-l+1];
  while( i<=m && j<=r)
  {
  if(arr[i]<=arr[j])
  temp[k++]=arr[i++];
  else
  temp[k++]=arr[j++];
  }
  
  while (i <= m)
  temp[k++]=arr[i++];

  
  while (j <= r)
  temp[k++]=arr[j++]; 
  
  int y=l;
  for(int i=0;i<(r-l+1);i++)
 { arr[y]=temp[i];
    y++;
 }  
}







No comments

darkmode