본문 바로가기
Algorithm

Merge Sort

by orioncsy 2022. 10. 11.
import java.util.*;

public class Solution { 
	public int[] mergeSort(int[] arr) {
		// TODO :
    //재귀로 구현
    if(arr.length==1) return arr;
    int half=arr.length/2;
    int arr1[]=Arrays.copyOf(arr, half);
    int arr2[]=Arrays.copyOfRange(arr, half, arr.length);
    arr1=mergeSort(arr1);
    arr2=mergeSort(arr2);
    int j=0, k=0;
    for(int i=0; i<arr.length;i++){
      if(j<arr1.length && k<arr2.length){
        if(arr1[j]<arr2[k]) arr[i]=arr1[j++];
        else arr[i]=arr2[k++];
      }
      else if(j>=arr1.length) arr[i]=arr2[k++];
      else if(k>=arr2.length) arr[i]=arr1[j++];
    }
    return arr;
	}
}

'Algorithm' 카테고리의 다른 글

Binary Search  (0) 2022.10.13
Heap Sort  (0) 2022.10.11
Radix Sort  (0) 2022.10.11
Insertion sort  (1) 2022.10.07
Bubble Sort  (0) 2022.10.06