External Exam Download Resources Web Applications Games Recycle Bin

merge sort


Recursively until the sort is complete:
  Divide the unsorted list into two sublists of about half the size
  Sort each of the two sublists
  Merge the two sorted sublists back into one sorted list
and in java:
public class mergeSort{
    public static void main(String[] args) {
        int[] array={22,1,14,-4,-43,146,59,71,54,3,3};
        mergeSort(array);
        //check result:
        for(int x=0; x<array.length; x++){System.out.println(array[x]);}
    }    
//***************************************
//mergeSortRecursion, to split up the array:
    public static void mergeSort(int[] inputArray) {
        int size = inputArray.length;
        if (size < 2)
            return;
        int mid = size / 2;
        int leftSize = mid;
        int rightSize = size - mid;
        int[] left = new int[leftSize];
        int[] right = new int[rightSize];
        for (int i = 0; i < mid; i++) {
            left[i] = inputArray[i];

        }
        for (int i = mid; i < size; i++) {
            right[i - mid] = inputArray[i];
        }
        mergeSort(left);
        mergeSort(right);
        merge(left, right, inputArray);
    }
    
//***************************************
//merge, to rejoin sorted fragments:
    public static void merge(int[] left, int[] right, int[] arr) {
        int leftSize = left.length;
        int rightSize = right.length;
        int i = 0, j = 0, k = 0;
        while (i < leftSize && j < rightSize) {
            if (left[i] <= right[j]) {
                arr[k] = left[i];
                i++;
                k++;
            } else {
                arr[k] = right[j];
                k++;
                j++;
            }
        }
        while (i < leftSize) {
            arr[k] = left[i];
            k++;
            i++;
        }
        while (j < rightSize) {
            arr[k] = right[j];
            k++;
            j++;
        }
    }
}