Created
June 20, 2014 15:52
-
-
Save lnicola/342f2e9816949feaf396 to your computer and use it in GitHub Desktop.
mergesort
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
int v[10]; | |
void mergesort(int l, int r) | |
{ | |
if (r > l) | |
{ | |
int aux[10], m = (l + r) / 2, i = l, j = m + 1, k = 0; | |
mergesort(l, m); | |
mergesort(m + 1, r); | |
while (i <= m && j <= r) | |
aux[k++] = v[i] < v[j] ? v[i++] : v[j++]; | |
while (i <= m) | |
aux[k++] = v[i++]; | |
while (j <= r) | |
aux[k++] = v[j++]; | |
while (r >= l) | |
v[r--] = aux[--k]; | |
} | |
} | |
void main() | |
{ | |
int a[10][10], n; | |
FILE *f = fopen("ms.txt", "rt"); | |
fscanf(f, "%d", &n); | |
for (int i = 0; i < n; i++) | |
for (int j = 0; j < n; j++) | |
fscanf(f, "%d", &a[i][j]); | |
fclose(f); | |
for (int i = 0; i < n; i++) | |
{ | |
for (int j = 0; j < n; j++) | |
printf("%d ", a[i][j]); | |
printf("\n"); | |
} | |
for (int i = 0; i < n; i++) | |
{ | |
for (int j = 0; j <= i; j++) | |
v[j] = a[j][i - j]; | |
mergesort(0, i); | |
for (int j = 0; j <= i; j++) | |
a[j][i - j] = v[j]; | |
} | |
for (int i = n; i < 2 * n - 1; i++) | |
{ | |
for (int j = n - 1; j > i - n; j--) | |
v[n - j - 1] = a[i - j][j]; | |
mergesort(0, 2 * n - i - 2); | |
for (int j = n - 1; j > i - n; j--) | |
a[i - j][j] = v[n - j - 1]; | |
} | |
printf("\n"); | |
for (int i = 0; i < n; i++) | |
{ | |
for (int j = 0; j < n; j++) | |
printf("%d ", a[i][j]); | |
printf("\n"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment