LISTING 8.5 Mergesort. java Implements the recursive merge sort algorithm. In th
ID: 3832123 • Letter: L
Question
LISTING 8.5 Mergesort. java Implements the recursive merge sort algorithm. In this version, copies of the subtables are made, sorted, and then merged. public class Mergesort Sort the array using the merge sort algorithm. pre: table contains Comparable objects. post table is sorted @param table The array to be sorted public static > void sort TCJ table) A table with one element is sorted already. if (table length 1) Split table into halves. int halfSize table length 2 TCJ left Table (ECJ) new Comparable half Size] TC] rightTable (ECJ) new ComparableCtable.length half Size] System. arraycopy(table, 0, leftTable, 0, halfSize); System. array copy (table, halfSize right Table, 0, table length halfSize); Sort the halves. sort (left Table) sort rightTable); Merge the halves. merge (table, leftTable rightTable) See Listing 8.4 for the merge method.Explanation / Answer
package sorts; public class MergeSort { public static void sort(T[] table) { if (table.length > 1) { int halfSize = table.length / 2; T[] leftTable = (T[]) new Comparable[halfSize]; T[] rightTable = (T[]) new Comparable[table.length - halfSize]; System.arraycopy(table, 0, leftTable, 0, halfSize); System.arraycopy(table, halfSize, rightTable, 0, table.length - halfSize); sort(leftTable); sort(rightTable); merge(table, leftTable, rightTable); } } private static void merge(T[] outputSequence, T[] leftTable, T[] rightTable) { int i = 0, j = 0, k = 0; while (iRelated Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.