10.归并排序

1)整体就是一个简单递归,左边排好序、右边排好序、让其整体有序
2)让其整体有序的过程里用了排外序方法
3)利用master公式来求解时间复杂度
4)归并排序的实质
时间复杂度O(N*logN),额外空间复杂度O(N)

void Merge(int arr[], int left, int mid, int right)
{
  if (!arr) return;
    
  int *pTemp = new int[right-left+1];
  int i = 0;
    
  int rightOneNum = mid + 1;
  while (left <= mid && rightOneNum <= right)
  {
    pTemp[i++] = arr[left] < arr[rightOneNum] ? arr[left++] : arr[rightOneNum++];
  }
    
  while (left <= mid)
  {
    pTemp[i++] = arr[left++];
  }
    
  while (rightOneNum <= right)
  {
    pTemp[i++] = arr[rightOneNum++];
  }
    
  for (int j = 0; j < right-left+1; ++j)
  {
    arr[left+j] = pTemp[j];
  }
    
  delete[] pTemp;
}

void MergeSort(int arr[], int left , int right)
{
	if (!arr) return;
   
    if (left == right) return;
    
    int mid = left + ((right - left)>>1);
    
    MergeSort(arr, left, mid);
    MergeSort(arr, mid+1, right);
    
    Merge(arr, left, mid, right);
    
}
posted @ 2022-09-09 09:56  test369  阅读(16)  评论(0编辑  收藏  举报