# ANSI C 中的合并排序算法

``````/* C program for Merge Sort */
#include <stdio.h>
#include <stdlib.h>

void printArray(int A[], int size) {
int i;
for (i = 0; i < size; i++)
printf("%d ", A[i]);
printf("\n");
}

void merge(int arr[], int l, int m, int r) {
int i, j, k;
int n1 = m - l + 1;
int n2 = r - m;

int L[n1 + 1], R[n2 + 1];

for (i = 1; i <= n1; i++) {
L[i] = arr[l + i - 1];
}
for (j = 1; j <= n2; j++) {
R[j] = arr[m + j];
}

L[n1 + 1] = 1.0 / 0.0;
R[n2 + 1] = 1.0 / 0.0;
i = 1;
j = 1;

for (k = l; k <= r; k++) {
if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
} else {
arr[k] = R[j];
j++;
}
}

// If I delete this the code stop "working". Why???
while (i < k && k < i) {
i++;
}
}

void mergeSort(int arr[], int left, int right) {

if (left < right) {
int middle = left + (right - left) / 2;

mergeSort(arr, left, middle);
mergeSort(arr, middle + 1, right);

merge(arr, left, middle, right);
}
}

int main() {
int arr[] = { 12, 11, 13, 5, 6, 7 };
int arr_size = sizeof(arr) / sizeof(arr[0]);

printf("Given array is \n");
printArray(arr, arr_size);

mergeSort(arr, 0, arr_size - 1);

printf("\nSorted array is \n");
printArray(arr, arr_size);
return 0;
}
``````

``````    L[n1 + 1] = 1.0 / 0.0;
R[n2 + 1] = 1.0 / 0.0;
``````

``````    L[n1 + 1] = INT_MAX;
R[n2 + 1] = INT_MAX;
``````

``````    int L[n1 + 2], R[n2 + 2]; // So we can use the `... + 1` elements.
``````

0 条评论