# Merge sort algorithm implemented in Java

The following is a merge sort algorithm implemented in Java, referencing Algorithms Unlocked by Thomas H. Cormen

I read some blogs from other CSDN bloggers, and I think some details can be optimized, such as avoiding overflow due to too long array length, and using mid = low + (high - low) / 2 for mid

For example, instead of creating a (high - low + 1) long array, you can create only the first half of the array[low...mid]

These small details can be optimized to increase the upper bound of the calculation and reduce space use by half.

```package sort_and_search;

import java.util.Random;

public class MergeSort {

public static void mergeSort(int[] array, int low, int high) {
int mid = low + (high - low) / 2;	// Another algorithm for mid = (high + low)/2 to avoid overflow
if(low < high) {
mergeSort(array, low, mid);	  // For array[low...mid]Merge Sort
mergeSort(array, mid+1, high);    // For array[mid+1...high] merge sort
mergeArray(array, low, mid, high);// fuse
}
return;
}

public static void mergeArray(int[] array, int low, int mid, int high) {
int[] temp = new int[mid-low+1];	  //To create a temporary array, just create the first half
for(int i = 0, j = low; i < temp.length; i++, j++) {
temp[i] = array[j];		  //Assigning values to temporary arrays
}
int i = 0, j = mid+1, m = low;
while(i < temp.length && j <= high) {     //Merge two ordered arrays
if(temp[i] <= array[j]) {	  //Less than or equal to is to maintain stability
array[m] = temp[i];
i++; m++;
continue;
}
else {
array[m] = array[j];
m++; j++;
continue;
}
}
while(i < temp.length)			  //Finally, fill in the remaining elements
array[m++] = temp[i++];

/*while(j <= high)
array[m++] = array[j++];
You don't really need to do this because array[j]==array[m]
*/

}

public static void main(String[] args) {
Random random = new Random();
int []array = new int;
System.out.println("We randomly create an array, the array is below: ");
for (int i = 0; i < array.length; i++) {
array[i] = random.nextInt(500);		//Generate Random Numbers up to 500
System.out.print(array[i]+" ");
}System.out.println();
System.out.println("After selection sort, the answer is: ");
mergeSort(array, 0, array.length-1);
for (int i : array) {
System.out.print(i+" ");
}System.out.println();
}

}```

Beginner algorithm, limited level, please correct any errors.

Tags: Java less

Posted on Fri, 10 Jul 2020 11:37:04 -0400 by netman182