The Official BLOG and Wiki for CustomMode.com
[ start | index | login ]
start > MergeSort

MergeSort

Created by dmitry. Last edited by dmitry, 4 years and 98 days ago. Viewed 396 times. #2
[diff] [history] [edit] [rdf]
labels
attachments
This question comes up on the interview quite often, here is my implementation of the quick merge sort algorithm in java that works:

/*
 * Created on Sep 21, 2004
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
package com.custommode;

/** * @author damelchenko * */ public class MergeSort { public static void main(String args[]) { int[] mParams = new int[args.length]; for (int i = 0; i < mParams.length; i++) { mParams[i] = new Integer(args[i]).intValue(); };

int[] mResults = sort(mParams);

for (int i = 0; i < mResults.length; i++) { System.out.print(mResults[i]); System.out.print(" "); }

}

/** * recursive sort method * * @param pUnsordetArray * @return returns sorted array */ public static int[] sort(int[] pUnsordetArray) {

if (pUnsordetArray.length <= 1) return pUnsordetArray;//it's sorted

int[] mLeftArray = new int[pUnsordetArray.length / 2 + pUnsordetArray.length % 2]; int[] mRighArray = new int[pUnsordetArray.length / 2];

for (int i = 0; i < pUnsordetArray.length / 2 + pUnsordetArray.length % 2; i++) { mLeftArray[i] = pUnsordetArray[i]; }

for (int i = 0; i < pUnsordetArray.length / 2; i++) { mRighArray[i] = pUnsordetArray[i + pUnsordetArray.length / 2 + pUnsordetArray.length % 2]; }

mLeftArray = sort(mLeftArray); mRighArray = sort(mRighArray);

int[] mResultMerge = merge(mLeftArray, mRighArray); return mResultMerge; }

public static int[] merge(int[] pLeftArray, int[] pRightArray) { int[] mResultMerge = new int[pLeftArray.length + pRightArray.length]; int mResultIndex = 0, mLowPointer = 0, mHighPointer = 0;

for (mResultIndex = 0; mResultIndex < mResultMerge.length; mResultIndex++) {

if(mLowPointer >= pLeftArray.length) { for(int j = mHighPointer; j < pRightArray.length; ) { mResultMerge[mResultIndex++] = pRightArray[j++]; } return mResultMerge; }

if(mHighPointer >= pRightArray.length) { for(int j = mLowPointer; j < pLeftArray.length; ) { mResultMerge[mResultIndex++] = pLeftArray[j++]; } return mResultMerge; }

if(pLeftArray[mLowPointer] < pRightArray[mHighPointer]) { mResultMerge[mResultIndex] = pLeftArray[mLowPointer++]; } else { mResultMerge[mResultIndex] = pRightArray[mHighPointer++]; } } return mResultMerge; } }

P.S. This implementation is not ideal, it uses java arrays and is very memory intensive (specially for large inputs). It was given to me as a requirement to use arrays, that's why I implemented it this way. Using java collections would be better idea.

no comments | post comment
custommode.com | ©2000-2005
webmaster at custommode dot com