Last active
August 17, 2022 16:23
-
-
Save omarzer0/ddde412afa212e464e97d445be0daca7 to your computer and use it in GitHub Desktop.
Merge Sort Algorithm using Java
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
import java.util.Arrays; | |
public class MergeSort { | |
public static void main(String[] args) { | |
int[] arr = new int[]{9, 3, 6, 7, 3, 2, 1, 5, 4, 7, 5}; | |
mergeSort(arr); | |
System.out.println(Arrays.toString(arr)); | |
} | |
public static void mergeSort(int[] inputArray) { | |
int inputLength = inputArray.length; | |
if (inputLength < 2) { | |
return; | |
} | |
int midIndex = inputLength / 2; // 11 => 5 , 6 | |
int[] leftHalf = new int[midIndex]; | |
int[] rightHalf = new int[inputLength - midIndex]; // 11 - 5 = 6 | |
// populate left array | |
for (int i = 0; i < midIndex; i++) { | |
leftHalf[i] = inputArray[i]; | |
} | |
// populate right array | |
for (int i = midIndex; i < inputLength; i++) { | |
rightHalf[i - midIndex] = inputArray[i]; // i = 5 we need index 0 => i - midIndex => 5 - 5 = 0 | |
} | |
mergeSort(leftHalf); | |
mergeSort(rightHalf); | |
merge(inputArray, leftHalf, rightHalf); | |
} | |
public static void merge(int[] inputArray, int[] leftHalf, int[] rightHalf) { | |
int leftSize = leftHalf.length; | |
int rightSize = rightHalf.length; | |
int i = 0, j = 0, k = 0; | |
while (i < leftSize && j < rightSize) { | |
if (leftHalf[i] < rightHalf[j]) { | |
inputArray[k] = leftHalf[i]; | |
i++; | |
} else { | |
inputArray[k] = rightHalf[j]; | |
j++; | |
} | |
k++; | |
} | |
// add the rest that haven't been added | |
while (i < leftSize) { | |
inputArray[k] = leftHalf[i]; | |
i++; | |
k++; | |
} | |
while (j < rightSize) { | |
inputArray[k] = rightHalf[j]; | |
j++; | |
k++; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment