본문 바로가기

2. 알고리즘 공부/JAVA 기본 알고리즘 구현

1. Merge Sort(병합정렬)

public class MergeSort {
	public static void mergeSort(int nums[], int helper[], int s, int e) {
		if (s < e) {
			int m = (s+e)/2;
			mergeSort(nums, helper, s, m);
			mergeSort(nums, helper, m+1, e);
			merge(nums, helper, s, m, e);
		}
	}
	public static void merge(int nums[], int helper[], int s, int m, int e) {
		for (int i = s; i <= e; i++) helper[i] = nums[i];
		int left = s, right = m+1, cur = s;
		while(left <= m && right <= e) 
			nums[cur++] = helper[left] <= helper[right]? helper[left++] : helper[right++];
		while(left <= m) nums[cur++] = helper[left++];		
	}
}