Mergesort in java

Here is a corrected version of your code: import java.io.*; import java.util.Arrays; public class MergeSort { public static void main(String[] args) throws IOException{ BufferedReader R = new BufferedReader(new InputStreamReader(System.in)); int arraySize = Integer.parseInt(R.readLine()); int[] inputArray = new int[arraySize]; for (int i = 0; i < arraySize; i++) { inputArray[i] = Integer.parseInt(R.readLine()); } mergeSort(inputArray); for (int … Read more

How to perform merge sort using LINQ?

There is no such method in LINQ. And I don’t think it’s possible to combine the existing methods to do exactly what you want (if it was, it would be overly complicated). But implementing such method yourself isn’t that hard: static IEnumerable<T> Merge<T>(this IEnumerable<T> first, IEnumerable<T> second, Func<T, T, bool> predicate) { // validation ommited … Read more

Non-Recursive Merge Sort

Non-recursive merge sort works by considering window sizes of 1,2,4,8,16..2^n over the input array. For each window (‘k’ in code below), all adjacent pairs of windows are merged into a temporary space, then put back into the array. Here is my single function, C-based, non-recursive merge sort. Input and output are in ‘a’. Temporary storage … Read more

‘MergeSort Algorithm’ – What’s the better implementation in JAVA? [closed]

Do a single allocation of the working/temp array and avoid copying of data during merge (unless moving a single remaining run from one array to the other). Bottom up merge sort example. package jsortbu; import java.util.Random; public class jsortbu { static void MergeSort(int[] a) // entry function { if(a.length < 2) // if size < … Read more

Why does Java’s Arrays.sort method use two different sorting algorithms for different types?

The most likely reason: quicksort is not stable, i.e. equal entries can change their relative position during the sort; among other things, this means that if you sort an already sorted array, it may not stay unchanged. Since primitive types have no identity (there is no way to distinguish two ints with the same value), … Read more

Multithreaded quicksort or mergesort

give a try to fork/join framework by Doug Lea: public class MergeSort extends RecursiveAction { final int[] numbers; final int startPos, endPos; final int[] result; private void merge(MergeSort left, MergeSort right) { int i=0, leftPos=0, rightPos=0, leftSize = left.size(), rightSize = right.size(); while (leftPos < leftSize && rightPos < rightSize) result[i++] = (left.result[leftPos] <= right.result[rightPos]) … Read more