C#

12.C# - 알고리즘 : 병합 (MEARGE)

Godffs 2009. 8. 12. 22:36
반응형
정수형 값이 저장된 두개의 배열을 더하여 하나로 묶은 다음 배열안에 있는
정수형 값을 작은 숫자 부터 큰 숫자까지 나타내는 예제 입니다.


 MEARGE.cs
using System;

public class MEARGE
{
    public static void Main()
    {
        //[1] Input : 원본 데이터가 정렬되어있다고 가정
        int[] first = { 1, 3, 5 };
        int[] second = { 2, 4 };
        //Mearge될 배열
        int[] mearge = new int[first.Length + second.Length];
        
        //병합정렬코드
        int i = 0; int j = 0; int k = 0;
        int M = first.Length;
        int N = second.Length;

        //[2] Process
        while (i < M && j < N) //모두 끝에 도달할 때까지
        {
            if (first[i] <= second[j]) {
                mearge[k++] = first[i++];
            }
            else { mearge[k++] = second[j++];
            }
        }
        while (i < M) //첫번째 배열이 끝까지 도달할 때까지
        {
            mearge[k++] = first[i++];
        }
        while (j< N) //첫번째 배열이 끝까지 도달할 때까지
        {
            mearge[k++] = second[j++];
        }
        //[3] Output
        for (int a=0;  a< mearge.Length; a++)
        {
            Console.Write(mearge[a]); //1,2,3,4,5
        }
        Console.WriteLine();
    }
}

결과화면


반응형