Created
September 4, 2019 03:56
-
-
Save kntmr/b62e3dcd6e64a8750a1b45d1f8f89b25 to your computer and use it in GitHub Desktop.
Merge sort algorithm
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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