Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Arrays;
- public class MergeSort {
- /**
- * Merges two arrays into one.
- *
- * @param array
- * array that contains the two arrays.
- * @param temp
- * temporary array that we will work with
- * @param low
- * lowest index value in the array
- * @param mid
- * middle index value in the array (represents break between low
- * and high values)
- * @param high
- * highest index value in the array
- */
- private static void merge(int[] array, int[] temp, int low, int mid,
- int high) {
- int i = low;
- int j = mid;
- for (int k = low; k < high; k++) {
- if (i == mid)
- temp[k] = array[j++]; // if low-mid array is empty
- else if (j == high)
- temp[k] = array[i++]; // if mid-high array is empty
- else if (array[j] > array[i])
- temp[k] = array[i++]; // i is lower so we put it in the array
- // first
- else
- temp[k] = array[j++]; // j is lower or equal to i, so we put it
- // in
- // the array first.
- }
- // now we need to copy back temp array to its place in array array
- for (int k = low; k < high; k++)
- array[k] = temp[k]; // we are copying only the numbers we just
- // merged.
- }
- private static void mergeSort(int[] array, int low, int high) {
- if (high - low == 1)
- return; // only one element in the array, return.
- int mid = low + (high - low) / 2; // find middle
- mergeSort(array, low, mid); // sort first part
- mergeSort(array, mid, high); // sort second part
- merge(array, new int[array.length], low, mid, high); // merge both parts
- }
- /**
- * Sorts the given list. (Not in place) Worst Case Performance O(nlogn) Best
- * Case Performance O(nlogn) Average Case Performance O(nlogn)
- *
- * @param array
- * list of int array.
- */
- public static void sortNumbers(int[] array) {
- mergeSort(array, 0, array.length);
- System.out.println(" " + Arrays.toString(array));
- }
- /**
- * Sample Test Run
- */
- public static void main(String[] args) {
- int[] list = { 156, 344, 54, 546, 767, 23, 34, 64, 234, 654, 234, 65,
- 234, 65, 87, 3, 5, 76, 24, 2, 3, 7, 9, 5, 34, 32, 4525, 345, 0 };
- sortNumbers(list);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement