Docstoc

Merge sort code java

Document Sample
Merge sort code java Powered By Docstoc
					package alghoritmshw;

/**
 *
 * @author Benjamin Talic
 */
public class MergeSort {

    public static void MergeSort(int[] A) {

        if (A.length <= 1)
            return;


        int[] PermutationArray = new int[A.length / 2];
        int[] PermutationArray2 = new int[A.length - A.length / 2];

        System.arraycopy(A, 0, PermutationArray, 0, A.length/2)
        System.arraycopy(A, A.length / 2, PermutationArray2, 0, (A.length
- A.length / 2));


        MergeSort(PermutationArray);
        MergeSort(PermutationArray2);


        int i = 0, j = 0, k = 0;
        while (i < PermutationArray.length && j <
PermutationArray2.length) {
            if (PermutationArray[i] < PermutationArray2[j]) {
                 A[k] = PermutationArray[i];
                 k++;
                 i++;
            } else {
                 A[k] = PermutationArray2[j];
                 k++;
                 j++;
            }
        }
        while (k < PermutationArray.length + PermutationArray2.length) {
            if (i < PermutationArray.length) {
                 A[k] = PermutationArray[i];
                 i++;
            } else {
                 A[k] = PermutationArray2[j];
                 j++;
            }
            k++;
        }
    }
}

				
DOCUMENT INFO
Shared By:
Categories:
Stats:
views:25
posted:11/22/2011
language:English
pages:1
Description: a java code for the merge sort algorithm