#29804:


pds3601o (findStenFaul)

學校 : 不指定學校
編號 : 185702
來源 : [67.165.112.98]
最後登入時間 :
2022-09-03 12:17:08
a104. 排序 -- yoooooooo | From: [114.136.98.5] | 發表日期 : 2022-04-02 20:12

#include <stdio.h>
#include <stdlib.h>

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

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

    i=0;
    j=0;
    k = l;

    while ( i < n1 && j < n2 ) {
        if (L[i] <= R[j]) {
            arr[k] = L[i++];
        } else {
            arr[k] = R[j++];
        }
        k++;
    }
    while ( i < n1 ) {arr[k++] = L[i++];}
    while ( j < n2 ) {arr[k++] = R[j++];}
}

void merge_sort(int *arr, int l, int r) {
    if ( l < r) {
        int m = l + (r-l)/2;
        merge_sort(arr, l, m);
        merge_sort(arr, m+1, r);
        merge(arr, l, m, r);
    }
}

int main() {
    int size;
    char ch;
    char input[2000] = {'\0'};

    while (scanf("%d", &size) != EOF) {

        int *list = calloc (size, sizeof(int));
        int i=0;

        while ( i < size ) {
            scanf(" %d", &list[i]);
            i++;
        }

        merge_sort(list, 0, size-1);

        for (i=0 ; i < size ; i++) { printf("%d ", list[i]); }
        printf("\n");
        
        free(list);
    }
    return 0;
}

 
ZeroJudge Forum