C语言归并排序

废话不多说直接上代码

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

/*
Description: 归并排序
Author: QinGQ
Datetime: 2021年3月8日20点03分 
*/

int Length;                                     //待排序数组长度
int *A;                                         //待排序数组
int *B;                                         //辅助数组B
void MergeSort(int *A, int low, int high);      //归并排序
void Merge(int *A, int low, int mid, int high); //合并子数组
void printnums(int *A);                         //打印数组

int main()
{
  puts("请输入待排序数组的长度:");
  scanf("%d", &Length);
  A = (int *)malloc(sizeof(int) * Length);
  B = (int *)malloc(sizeof(int) * Length);
  puts("请输入待排序数组:");
  for (int i = 0; i < Length; i++)
  {
    scanf("%d", &A[i]);
  }
  MergeSort(A, 0, Length - 1);
  printnums(A);
  system("pause");
  return 0;
}

void Merge(int *A, int low, int mid, int high)
{
  //将A中的元素复制到辅助数组B中
  for (int i = low; i <= high; i++)
  {
    B[i] = A[i];
  }
  int i, j, k;
  //依次挑选两个子数组的较小的元素放入原数组,知道其中一个被挑完
  for (i = low, j = mid + 1, k = i; i <= mid && j <= high; k++)
  {
    if (B[i] <= B[j])
    {
      A[k] = B[i++];
    }
    else
    {
      A[k] = B[j++];
    }
  }
  //将剩余的那个数组全部放回原数组
  while (i <= mid)
  {
    A[k++] = B[i++];
  }
  while (j <= high)
  {
    A[k++] = B[j++];
  }
}

void MergeSort(int *A, int low, int high)
{
  if (low < high)
  {
    int mid = (low + high) / 2;  //从中间划分两个子数组
    MergeSort(A, low, mid);      //递归排序左边子数组
    MergeSort(A, mid + 1, high); //递归排序右边子数组
    Merge(A, low, mid, high);    //归并
  }
}

void printnums(int *A)
{
  for (int i = 0; i < Length; i++)
  {
    printf("%d ", A[i]);
  }
  puts("");
}

如有错误欢迎指正!

posted @ 2021-03-12 19:37  闻风听雨  阅读(118)  评论(0编辑  收藏  举报