#include <stdio.h>
int n = 7;
int bil[] = {5, 3, 8, 4, 7, 2, 1};
void swap(int first, int second) {
int tampung = bil[second];
int i;
for (i = second - 1; i >= first; i--) {
bil[i + 1] = bil[i];
}
bil[first] = tampung;
}
void mergeSort(int startBawah, int endAtas) {
if (startBawah >= endAtas) {
return;
}
int middle = (startBawah + endAtas) / 2;
int endBawah = middle;
int startAtas = middle + 1;
mergeSort(startBawah, endBawah);
mergeSort(startAtas, endAtas);
while ((startBawah <= endBawah) && (startAtas <= endAtas)) {
if (bil[startBawah] > bil[startAtas]) {
swap(startBawah, startAtas);
startBawah++;
startAtas++;
endBawah++;
} else {
startBawah++;
}
}
}
int main() {
mergeSort(0, n - 1);
int x;
for (x = 0; x < n; x++) {
printf("%d ", bil[x]);
}
return 0;
}
No comments:
Post a Comment