廢話很少說直接上代碼
#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("");
}
若有錯誤歡迎指正!