Created
October 1, 2015 15:28
-
-
Save wicksome/96c7054a85cf6b757056 to your computer and use it in GitHub Desktop.
병합정렬
This file contains hidden or 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 kr.opid.sorting; | |
| public class MergeSort { | |
| public static void main(String args[]) { | |
| int[] array = new int[10]; | |
| array[0] = 33; | |
| array[1] = 11; | |
| array[2] = 99; | |
| array[3] = 1; | |
| array[4] = 22; | |
| array[5] = 88; | |
| array[6] = 55; | |
| array[7] = 44; | |
| array[8] = 66; | |
| array[9] = 77; | |
| System.out.println("before)"); | |
| displayArray(array); | |
| System.out.println("after)"); | |
| array = mergeSort(array); | |
| displayArray(array); | |
| } | |
| public static int[] mergeSort(int[] list) { | |
| if (list.length <= 1) { | |
| return list; | |
| } | |
| // Split the array in half | |
| int[] first = new int[list.length / 2]; | |
| int[] second = new int[list.length - first.length]; | |
| System.arraycopy(list, 0, first, 0, first.length); | |
| System.arraycopy(list, first.length, second, 0, second.length); | |
| // Sort each half | |
| mergeSort(first); | |
| mergeSort(second); | |
| // Merge the halves together, overwriting the original array | |
| merge(first, second, list); | |
| return list; | |
| } | |
| private static void merge(int[] first, int[] second, int[] result) { | |
| // Merge both halves into the result array | |
| // Next element to consider in the first array | |
| int iFirst = 0; | |
| // Next element to consider in the second array | |
| int iSecond = 0; | |
| // Next open position in the result | |
| int j = 0; | |
| // As long as neither iFirst nor iSecond is past the end, move the | |
| // smaller element into the result. | |
| while (iFirst < first.length && iSecond < second.length) { | |
| if (first[iFirst] < second[iSecond]) { | |
| result[j] = first[iFirst]; | |
| iFirst++; | |
| } else { | |
| result[j] = second[iSecond]; | |
| iSecond++; | |
| } | |
| j++; | |
| } | |
| // copy what's left | |
| System.arraycopy(first, iFirst, result, j, first.length - iFirst); | |
| System.arraycopy(second, iSecond, result, j, second.length - iSecond); | |
| } | |
| static void displayArray(int[] arr) { | |
| for (int i = 0; i < arr.length; i++) { | |
| System.out.print(arr[i] + " "); | |
| } | |
| System.out.println(); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment