Skip to content

Instantly share code, notes, and snippets.

@CoolgaDV
Created April 24, 2020 13:05
Show Gist options
  • Select an option

  • Save CoolgaDV/8a0714766c9aca3b0fb8170957d16c5a to your computer and use it in GitHub Desktop.

Select an option

Save CoolgaDV/8a0714766c9aca3b0fb8170957d16c5a to your computer and use it in GitHub Desktop.
Merge sort (interview task)
package interview;
public class MergeSort {
public void sort(int[] data) {
if (data == null || data.length <= 1) {
return;
}
sort(data, 0, data.length - 1);
}
private void sort(int[] data, int low, int high) {
if (high == low) {
return;
}
int half = (low + high) / 2;
sort(data, low, half);
sort(data, half + 1, high);
int[] result = new int[high - low + 1];
int resultIndex = 0;
int lowIndex = low;
int highIndex = half + 1;
while (lowIndex <= half && highIndex <= high) {
result[resultIndex++] = data[lowIndex] < data[highIndex]
? data[lowIndex++]
: data[highIndex++];
}
while (lowIndex <= half) {
result[resultIndex++] = data[lowIndex++];
}
while (highIndex <= high) {
result[resultIndex++] = data[highIndex++];
}
System.arraycopy(result, 0, data, low, result.length);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment