(알고리즘) MergeSort에서 반복되는 코드를 줄이는 한 가지 방법

  public int[] mergeArrays(int[] myArray, int[] alicesArray) {
    // 조건 myArray 와 alicesArray둘다 각각 이미 정렬되어 있어야한다.
    // set up our mergedArray
    int[] mergedArray = new int[myArray.length + alicesArray.length];

    int currentIndexAlices = 0;
    int currentIndexMine   = 0;
    int currentIndexMerged = 0;

    while (currentIndexMerged < mergedArray.length) {

        boolean isMyArrayExhausted = currentIndexMine >= myArray.length;
        boolean isAlicesArrayExhausted = currentIndexAlices >= alicesArray.length;

        // case: next comes from my array
        // my array must not be exhausted, and EITHER:
        // 1) alice's array IS exhausted, or
        // 2) the current element in my array is less
        //    than the current element in alice's array
        if (!isMyArrayExhausted && (isAlicesArrayExhausted
                || (myArray[currentIndexMine] < alicesArray[currentIndexAlices]))) {

            mergedArray[currentIndexMerged] = myArray[currentIndexMine];
            currentIndexMine++;

        // case: next comes from alice's array
        } else {
            mergedArray[currentIndexMerged] = alicesArray[currentIndexAlices];
            currentIndexAlices++;
        }

        currentIndexMerged++;
    }

    return mergedArray;
}

댓글

이 블로그의 인기 게시물

(네트워크)폴링방식 vs 롱 폴링방식

(ElasticSearch) 결과에서 순서 정렬

(18장) WebSocekt과 STOMP를 사용하여 메시징하기