summaryrefslogtreecommitdiff
path: root/ss2016/algodat/01/MergeSort.java
blob: 97f7cfa16a72a51638beea2535ed994d2929656a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import java.util.*;

class MergeSort {
    public static void mergeSort(int[] a, int from, int to) {
        if (from >= to)
            return;
        
        int mid = (from + to) / 2;
        mergeSort(a, from, mid);
        mergeSort(a, mid + 1, to);
        merge(a, from, mid, to);
    }

    public static void merge(int[] a, int from, int mid, int to) {
        int[] b = new int[to - from + 1];

        int i, j;
        i = from;
        j = mid + 1;
        
        for (int k = 0; k < b.length; k++) {
            if (j > to || (i <= mid && a[i] < a[j])) {
                b[k] = a[i];
                i++;
            } else {
                b[k] = a[j];
                j++;
            }
        }

        for (int k = 0; k < b.length; k++) {
            a[k + from] = b[k];
        }
    }
    
    public static void mergeSort(int[] a) {
        mergeSort(a, 0, a.length - 1);
    }
    
    public static void main (String[] argv) {
        int[] a = new int[argv.length];
        for (int i = 0; i < argv.length; i++)
            a[i] = Integer.parseInt(argv[i]);
        
        mergeSort(a);
        System.out.println(Arrays.toString(a));
    }
}