260102 TIL (알고리즘)

제갈도원·2026년 1월 24일

TIL

목록 보기
9/17

재귀함수

함수가 자기 자신을 호출하도록 하는 프로그래밍 기법
기저 조건 : 재귀 호출을 멈추는 조건
재귀 조건 : 자기 자신을 호출하는 부분
재귀로 가능한 것ㅇ르 반복문으로도 해결할 수 있다.
반복문으로 해결하는 문제를 모두 재귀로 해결할 수는 없다.

팩토리얼 예제 코드

public class TEST
{
    static void Factorial(int num)
    {
        int result = 1;

        for (int i = 1; i <= num; i++)
        {
            result *= i;
        }
        Console.WriteLine(result);
    }

    static int Factorial2(int num2)
    {
        // 기저 조건
        if (num2 == 1)
        {
            Console.WriteLine(1);
        }

        // 재귀 조건
        return num2 * Factorial2(num2 - 1);
    }
}
5 * Factorial2(4)
4 * Factorial2(3)
3 * Factorial2(2)
2 * Factorial2(1)
1
=> 120

알고리즘 실천

버블 정렬

namespace ConsoleApp1
{
    internal class Bubble_Sort
    {
        static void Main()
        {
            int[] arr = { 7, 5, 2, 4, 3 };
            Console.WriteLine("정렬 전:");
            Console.WriteLine(string.Join(", ", arr));
            BubbleSort(arr);
            Console.WriteLine("정렬 후:");
            Console.WriteLine(string.Join(", ", arr));

        }

        // 버블 정렬
        // 인접한 두 원소를 비교하여
        // 큰 원소를 뒤로 보내는 과정을 반복

        // 7, 5, 2, 4, 3
        // i = 0 : 5, 2, 4, 3, 7
        // i = 1 : 2, 4, 3, 5, 7
        // i = 2 : 2, 3, 4, 5, 7
        // i = 3 : 2, 3, 4, 5, 7
        public static void BubbleSort(int[] arr)
        {
            int n = arr.Length;

            for (int i = 0; i < n - 1; i++) // 총 몇 번 반복할지
            {
                for (global::System.Int32 j = 0; j < n - 1; j++) // 옆집이랑 비교
                {
                    if (arr[j] > arr[j + 1]) // 왼쪽이 오른쪽 보다 크다면
                    {
                        // 교환
                        int temp = arr[j];
                        arr[j] = arr[j + 1];
                        arr[j + 1] = temp;
                    }
                }
            }
        }
    }
}

선택 정렬

static void Main()
{
    int[] arr = { 7, 5, 2, 4, 3 };
    Console.WriteLine("정렬 전:");
    Console.WriteLine(string.Join(", ", arr));
    SelectSort(arr);
    Console.WriteLine("정렬 후:");
    Console.WriteLine(string.Join(", ", arr));
}

public static void SelectSort(int[] arr)
{
    int n = arr.Length;
    for (int i = 0; i < n - 1; i++)
    {
        // 현재 위치를 최소값으로 가정
        int minIndex = i;
        // 나머지 요소들 중에서 최소값 찾기
        for (int j = i + 1; j < n; j++)
        {
            if (arr[j] < arr[minIndex])
            {
                minIndex = j;
            }
        }
        // 최소값을 현재 위치로 교환
        if (minIndex != i)
        {
            int temp = arr[i];
            arr[i] = arr[minIndex];
            arr[minIndex] = temp;
        }
    }
}

퀵 정렬

namespace ConsoleApp1
{
    internal class Quick_Sort
    {

        public static void QuickSort(int[] arr, int low, int high)
        {
            if (low < high)
            {
                int pivotIndex = Partition(arr, low, high);

                QuickSort(arr, low, pivotIndex - 1);
                QuickSort(arr, pivotIndex + 1, high);
            }
        }

        private static int Partition(int[] arr, int low, int high)
        {
            int pivot = arr[high];
            int i = low - 1;

            for (int j = low; j < high; j++)
            {
                if (arr[j] < pivot)
                {
                    i++;
                    int temp = arr[i];
                    arr[i] = arr[j];
                    arr[j] = temp;
                }
            }

            return i + 1;
        }

    }
}

퀵 정렬 풀이

맨왼쪽을 기준으로 p 를 잡고 
L은 P 보다 큰지
R은 P 보다 작은지 
-> 위치 변경

1. 5 2 9 7 3 1 6
   p L L     R R    9와 1이 적합 -> 변경

2. 5 2 1 7 3 9 6
   p L L L R R R    7과 3이 적합 -> 변경

3. 5 2 1 3 7 9 6
   P L L L L  
         R R R R    R, L 이 위치가 바뀜 -> P, R 변경 
         R L

4. 3 2 1 5 7 9 6    5를 기준으로 왼쪽은 5보다 작고 오른쪽은 6보다 큼

5를 기준으로 나눔 3 2 1 |5| 7 9 6

오른쪽, 왼쪽 똑같이 반복
3 2 1 :  
3을 피벗으로 잡음 -> 3보다 큰 값 없음, 3보다 작은 값 1 바로 찾음 -> 큰 값 찾다가 서로 만남 -> 1 2 3 

7 9 6 :
7을 피벗 -> 9는 7보다 크고 6은 7보다 작음 9 6 체인지 ->
위와 같은 상황으로 P R 체인지 -> 7 9 6

1 2 3 4 5 6 7 8 9

0개의 댓글