#include<stdio.h>
typedef struct Array
{
int key;
}Array;
#define LENGTH 8
void Merge(Array A[],int low,int mid,int high);
void MergeSort(Array A[],int low , int high);
int main(void) {
int arr[LENGTH] = { 312,214,21,42,3,2325,23,15 };
int index = 1;
Array A[LENGTH+1];
while (index<=LENGTH){
A[index].key = arr[index - 1];
printf("排序前:%d\n",A[index].key);
index++;
}
MergeSort(A,1,LENGTH);
printf("**************************\n");
index = 1;
while (index <= LENGTH) {
printf("排序后:%d\n", A[index].key);
index++;
}
return 0;
}
void Merge(Array A[], int low, int mid, int high) {
Array *B = (Array *)malloc((LENGTH) * sizeof(Array));
int i, j, k;
for (k = low; k <= high;k++) {
B[k] = A[k];
}
for (i = low, j = mid + 1, k = i; i <= mid&&j <= high; k++) {
if (B[i].key <= B[j].key) {
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(Array 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);
}
}
C:C的排序算法:归并排序(MergeSort)
最新推荐文章于 2023-01-13 12:29:28 发布