Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

[JAVA] fix errors import java.util.Comparator; public class mergeSort { public static void mergeSort(E[] list, Comparator

[JAVA]

fix errors

import java.util.Comparator;

public class mergeSort {

public static void mergeSort(E[] list, Comparator comparator)

{

if(list.length > 1 )

{

E[] firstHalf = (E[]) new Comparable[list.length/2];

System.arraycopy(list,0,firstHalf,0,list.length / 2);

mergeSort(firstHalf, comparator);

int secondHalfLength = list.length - list.length / 2;

E[] secondHalf = (E[]) new Comparable[secondHalfLength];

System.arraycopy(list, list.length / 2, secondHalf, 0, secondHalfLength);

mergeSort(secondHalf, comparator);

E[] temp = merge(firstHalf, secondHalf, comparator);

System.arraycopy(temp, 0, list, 0, temp.length);

System.out.println("Merge sort: ");

for(E a : temp)

System.out.println(a);

}

}

private static E[] merge(E[] list1, E[] list2, Comparator comparator)

{

E[] temp = (E[]) new Comparable[list1.length + list2.length];

int current1 = 0;

int current2 = 0;

int current3 = 0;

while(current1 < list1.length && current2 < list2.length)

{

if(comparator.compare(list1[current1], list2[current2] < 0)

temp[current3++] = list1[current1++];

else

temp[current3++] = list2[current2++];

}

while(current1 < list1.length)

temp[current3++] = list1[current1++];

while(current2 < list2.length)

temp[current3++] = list2[current2++];

return temp;

}

public static void main(String args[]){

Integer[] list = {2,3,2,5,6,1,-2,3,14,12};

mergeSort(list);

}

}

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image_2

Step: 3

blur-text-image_3

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Beginning Databases With PostgreSQL From Novice To Professional

Authors: Richard Stones, Neil Matthew

2nd Edition

1590594789, 978-1590594780

More Books

Students also viewed these Databases questions

Question

Provide examples of KPIs in Human Capital Management.

Answered: 1 week ago

Question

What are OLAP Cubes?

Answered: 1 week ago