[java] 인터페이스를 사용하여 알고리즘 구현하기

자바에서 인터페이스(interface)는 클래스의 특정 동작을 서술하는 추상화된 형태를 제공합니다. 이러한 특징은 알고리즘을 구현하는 데 매우 유용하게 사용될 수 있습니다.

다음은 Bubble Sort 알고리즘을 인터페이스를 활용하여 구현하는 예제입니다.

BubbleSort 인터페이스 정의하기

public interface BubbleSort {
    public void sort(int[] arr);
}

BubbleSortImpl 클래스로 구현하기

public class BubbleSortImpl implements BubbleSort {
    @Override
    public void sort(int[] arr) {
        int n = arr.length;
        for (int i = 0; i < n-1; i++)
            for (int j = 0; j < n-i-1; j++)
                if (arr[j] > arr[j+1]) {
                    // Swap arr[j+1] and arr[i] 
                    int temp = arr[j];
                    arr[j] = arr[j+1];
                    arr[j+1] = temp;
                }
    }
}

알고리즘 사용하기

public class Main {
    public static void main(String[] args) {
        int[] arr = {64, 34, 25, 12, 22, 11, 90};
        BubbleSort bubbleSort = new BubbleSortImpl();
        bubbleSort.sort(arr);
        System.out.println("Sorted array: " + Arrays.toString(arr));
    }
}

이제 인터페이스를 사용하여 알고리즘을 구현하고, 해당 인터페이스를 구현하는 클래스를 만들어서 해당 알고리즘을 사용할 수 있습니다. 이러한 접근 방식은 코드의 유연성과 재사용성을 높여줍니다.

참고 문헌: