Question: JAVA PROGRAMMING HELP WITH MERGESORT METHOD Can someone please tell me what's wrong with my class? The supposedly sorted array isn't sorted. import java.util.Arrays; public

JAVA PROGRAMMING HELP WITH MERGESORT METHOD

Can someone please tell me what's wrong with my class? The supposedly sorted array isn't sorted.

import java.util.Arrays; public class MergeSort { public static int[] mergeSort(int [] a) { if (a.length <= 1) { return a; } int[] left = Arrays.copyOfRange(a, 0, a.length/2); int[] right = Arrays.copyOfRange(a, a.length/2, a.length); mergeSort(left); mergeSort(right); int [] result = merge(a, left, right); return result; } public static int[] merge(int [] a, int [] left, int [] right) { int [] result = new int[a.length]; int i = 0; int j = 0; int k =0; while(i < left.length || j < right.length){ if(i < left.length && j < right.length){ if(left[i] < right[j]){ result[k] = left[i]; i++; k++; }else{ result[k] = right[j]; k++; j++; } }else if(i < left.length){ result[k] = left[i]; k++; i++; }else if(j < right.length){ result[k] = right[j]; k++; j++; } } return result; } public static void main(String args[]){ int [] a = {8,7,2,3,6,5,1,2}; System.out.println("Unsorted array: "+ Arrays.toString(a)); int[] result = mergeSort(a); System.out.println("Sorted array: "+ Arrays.toString(result)); } } 

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!