Tuesday, December 7, 2010

Insertion Sort and Merge Sort in Java

Well it's my homework in DAA (Design and Analysis of Algorithms)
Talking about the algorithms, itself is brought from the book that we've used
which is "Introduction to Algorithms 3rd edition"
It's a good book, but I do weak in maths somehow.
So, probably there is some of them I couldn't understand right away.
It's bad to have a worst logic and maths skill, you know?
whatever, let's see the code that I have written using Java.
(Somebody said that they doesn't like Java because of its performance,
But I don't. I prefer it than C/C++ in some way.)

Insertion Sort
public static void insertionSort_2(int x[]) {
        int i, j, key;
        for (j = 1; j < x.length; j++) {
            key = x[j];  
            i = j - 1; 
            while (i >= 0 && x[i] > key) { 
                x[i + 1] = x[i]; 
                i = i - 1; .
            }
            x[i + 1] = key; 
        }
    }
This one works based on the algorithms of insertion sort. First we find the key.
then we lock the key so we won't get confuse between
the length of array we are caring and the one that is still out of our sight.
after that we just sorting it, by compare the value of an array, one by one.
when it have sorted, we just change the key. moving to the next one until the whole array is sorted.

Merge Sort
public static void merge_sort(int y[], int p, int r) {
        if (r > p) {
            int q = (p + r) / 2;
            merge_sort(y, p, q);
            merge_sort(y, q + 1, r);
            merge(y, p, q, r);
        }
    }
 Merge method
public static void merge(int y[], int p, int q, int r) {
        int n1 = q - p + 2;
        int n2 = r - q + 1;
        int i, j, k;
        int []left = new int[n1];
        int []right = new int[n2];
        //Cp y to left array
        for (i = 0; i < n1 - 1; i++) {
            left[i] = y[p + i];
        }
        left[n1 - 1] = INF;
        //Cp y to right array
        for (i = 0; i < n2 - 1; i++) {
            right[i] = y[q + 1 + i];
        }
        right[n2 - 1] = INF;
        i = 0;
        j = 0;
        for (k = p; k <= r; k++) {
            if (left[i] <= right[j]) {
                y[k] = left[i];
                i++;
            } else {
                y[k] = right[j];
                j++;
            }
        }
    }
For merge sort, there are two method you need.
The first one is for divide an array into separate two of them.
Another one is for merging them together.
I won't explain it clearly because it will take me a while to try to explain it.
As you can see that I'm not English native, so It's quite hard to write.

And It's all for tonight. I'm late for my bed again.

Thanks for reading
:)

No comments:

Post a Comment