import java.util.Arrays; public class MergeSort { public int[] mergeSort(int[] arr) { if(arr.length < 2) return arr; int[]l = Arrays.copyOfRange(arr, 0, arr.length/2+(arr.length%2==1?1:0)); int[]r = Arrays.copyOfRange(arr, arr.length/2+(arr.length%2==1?1:0),arr.length); int[] arrt = sort(mergeSort(l), mergeSort(r)); printArray(arrt); return arrt; } public int[] sort(int l[], int r[]) { if(l.length == 0 && r.length == 0) return l; if(l.length == 0 && r.length > 0) return r; if(r.length == 0 && l.length > 0) return l; int[] newarr = new int[l.length + r.length]; int lp = 0; int rp = 0; int np = 0; while(lp < l.length && rp < r.length) { if(l[lp] < r[rp]) { newarr[np++] = l[lp++]; } else { newarr[np++] = r[rp++]; } } while(lp < l.length) {newarr[np++] = l[lp++];} while(rp < r.length) {newarr[np++] = r[rp++];} return newarr; } public void printArray(int arr[]) { System.out.println(); for(int i = 0; i < arr.length; ++i) { System.out.print(" "); System.out.print(arr[i]); } } public static void main(String[] args) { MergeSort ob = new MergeSort(); int arr[] = { 64, 34, 25, 12, 22, 11, 90 }; System.out.println("Sorted array"); ob.printArray(ob.mergeSort(arr)); } }
0 Comments
|
This is a collection of interview prep programs, online resources that were used in my Java classes. The Java classes were taught years ago, hence the material is likely outdated, I will make an effort to go through it and update as time permits Categories |