Skip to content

Instantly share code, notes, and snippets.

@kntmr
Created September 4, 2019 03:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kntmr/b62e3dcd6e64a8750a1b45d1f8f89b25 to your computer and use it in GitHub Desktop.
Save kntmr/b62e3dcd6e64a8750a1b45d1f8f89b25 to your computer and use it in GitHub Desktop.
Merge sort algorithm
package com.example.demo;
public class MergeSort {
void mergeSort(int[] a, int[] temp, int left, int right) {
if (left >= right) return;
int mid = (left + right) / 2;
mergeSort(a, temp, left, mid);
mergeSort(a, temp, mid + 1, right);
merge(a, temp, left, right, mid);
}
void merge(int[] a, int[] temp, int left, int right, int mid) {
for (int i = left; i <= right; i++) {
temp[i] = a[i];
}
int currentLeft = left;
int currentRight = mid + 1;
int index = left;
while (currentLeft <= mid && currentRight <= right) {
if (temp[currentLeft] <= temp[currentRight]) {
a[index] = temp[currentLeft];
currentLeft++;
} else {
a[index] = temp[currentRight];
currentRight++;
}
index++;
}
for (int i = 0; i <= mid - currentLeft; i++) {
a[index + i] = temp[currentLeft + i];
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment