package com.imaginea.ds.practice;
/*
*MergeSort
* Worst case performance O(n log n)
* Best case performance O(n log n) typical, O(n) natural variant
* Average case performance O(n log n)
* Worst case space complexity O(n) auxiliary
*/
public class MergeSortExample {
static int[] arr = {45,23,11,89,77,98,4,28,65,43};
public static void main(String[] args) {
doMergeSort(0, arr.length-1);
for(int num:arr){
System.out.print(num+" ");
}
}
private static void doMergeSort(int lowerIdx, int higherIdx){
if(lowerIdx < higherIdx){
int middleIdx = lowerIdx + (higherIdx - lowerIdx)/2;
doMergeSort(lowerIdx, middleIdx);
doMergeSort(middleIdx+1, higherIdx);
mergeArray(lowerIdx, middleIdx, higherIdx);
}
}
private static void mergeArray(int lowerIdx, int middleIdx, int higherIdx){
int i=lowerIdx;
int j=middleIdx+1;
int k=lowerIdx;
int[] tmpArr= new int[higherIdx+1];
for(int idx=lowerIdx;idx<=higherIdx; idx++){
tmpArr[idx]=arr[idx];
}
while(i<=middleIdx && j<=higherIdx){
if(tmpArr[i] <= tmpArr[j]){
arr[k]=tmpArr[i];
i++;
}else{
arr[k]=tmpArr[j];
j++;
}
k++;
}
while(i <= middleIdx){
arr[k]=tmpArr[i];
k++;
i++;
}
}
}
Friday, May 22, 2015
Merge Sort Java Code
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment