learn/Algorithm

정렬 (Sorting)

사겅이 2023. 9. 25. 12:09

출처 : https://d2.naver.com/helloworld/0315536

데이터를 특정한 순서로 정리하는 방법

 

  • 선택 정렬 (Selection Sort): 가장 작은 값을 선택하여 맨 앞으로 이동시키는 방식으로 정렬 

출처 : https://hyo-ue4study.tistory.com/68

public class SelectionSortTest {
    public static void selectionSort(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;
                }
            }
            int temp = arr[minIndex];
            arr[minIndex] = arr[i];
            arr[i] = temp;
        }
    }

    public static void main(String[] args) {
        int[] arr = {64, 25, 12, 22, 11};
        selectionSort(arr);
        for (int num : arr) {
            System.out.print(num + " ");
        }
    }
}

 

  • 삽입 정렬 (Insertion Sort): 배열을 정렬된 부분과 정렬되지 않은 부분으로 나누고, 정렬되지 않은 값을 적절한 위치에 삽입하여 정렬

출처 : https://hyo-ue4study.tistory.com/68

public class InsertionSortTest {
    public static void insertionSort(int[] arr) {
        int n = arr.length;
        for (int i = 1; i < n; i++) {
            int key = arr[i];
            int j = i - 1;
            while (j >= 0 && arr[j] > key) {
                arr[j + 1] = arr[j];
                j--;
            }
            arr[j + 1] = key;
        }
    }

    public static void main(String[] args) {
        int[] arr = {64, 25, 12, 22, 11};
        insertionSort(arr);
        for (int num : arr) {
            System.out.print(num + " ");
        }
    }
}
 
  • 버블 정렬 (Bubble Sort): 인접한 두 요소를 비교하고 필요한 경우 위치를 교환하여 배열을 정렬하며 이 과정을 반복하여 가장 큰 값이 뒤로 이동

출처 : https://hyo-ue4study.tistory.com/68

public class BubbleSortTest {
    public static void bubbleSort(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]) {
                    int temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                }
            }
        }
    }

    public static void main(String[] args) {
        int[] arr = {64, 25, 12, 22, 11};
        bubbleSort(arr);
        for (int num : arr) {
            System.out.print(num + " ");
        }
    }
}

 

  • 병합 정렬 (Merge Sort): 분할 정복 방법을 사용하여 배열을 반으로 나눈 후, 각각을 정렬하고 다시 병합하여 정렬된 배열을 생성

출처 : https://hyo-ue4study.tistory.com/68

 
import java.util.Arrays;

public class MergeSortTest {
    public static void mergeSort(int[] arr) {
        if (arr.length > 1) {
            int mid = arr.length / 2;
            int[] left = Arrays.copyOfRange(arr, 0, mid);
            int[] right = Arrays.copyOfRange(arr, mid, arr.length);

            mergeSort(left);
            mergeSort(right);

            merge(arr, left, right);
        }
    }

    public static void merge(int[] arr, int[] left, int[] right) {
        int i = 0, j = 0, k = 0;
        while (i < left.length && j < right.length) {
            if (left[i] < right[j]) {
                arr[k++] = left[i++];
            } else {
                arr[k++] = right[j++];
            }
        }

        while (i < left.length) {
            arr[k++] = left[i++];
        }

        while (j < right.length) {
            arr[k++] = right[j++];
        }
    }

    public static void main(String[] args) {
        int[] arr = {38, 27, 43, 3, 9, 82, 10};
        mergeSort(arr);
        System.out.println(Arrays.toString(arr));
    }
}

 

  • 퀵 정렬 (Quick Sort): 분할 정복 방식을 사용하며, 피벗(pivot)을 기준으로 배열을 분할하고 각 부분을 정렬하며  빠른 정렬 속도로 유명합니다.

출처 : https://hyo-ue4study.tistory.com/68

import java.util.Arrays;

public class QuickSortTest {
    public static void quickSort(int[] arr, int low, int high) {
        if (low < high) {
            int pi = partition(arr, low, high);
            quickSort(arr, low, pi - 1);
            quickSort(arr, pi + 1, high);
        }
    }

    public 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;
            }
        }
        int temp = arr[i + 1];
        arr[i + 1] = arr[high];
        arr[high] = temp;
        return i + 1;
    }

    public static void main(String[] args) {
        int[] arr = {38, 27, 43, 3, 9, 82, 10};
        quickSort(arr, 0, arr.length - 1);
        System.out.println(Arrays.toString(arr));
    }
}

 

  • 힙 정렬 (Heap Sort): 최대 힙 또는 최소 힙을 사용하여 요소를 정렬하는 방식으로, 힙 트리를 구축하고 루트 노드를 교환하여 정렬

출처 : https://hyo-ue4study.tistory.com/68

import java.util.Arrays;

public class HeapSortTest {
    public static void heapSort(int[] arr) {
        int n = arr.length;
        for (int i = n / 2 - 1; i >= 0; i--) {
            heapify(arr, n, i);
        }

        for (int i = n - 1; i > 0; i--) {
            int temp = arr[0];
            arr[0] = arr[i];
            arr[i] = temp;
            heapify(arr, i, 0);
        }
    }

    public static void heapify(int[] arr, int n, int i) {
        int largest = i;
        int left = 2 * i + 1;
        int right = 2 * i + 2;

        if (left < n && arr[left] > arr[largest]) {
            largest = left;
        }

        if (right < n && arr[right] > arr[largest]) {
            largest = right;
        }

        if (largest != i) {
            int swap = arr[i];
            arr[i] = arr[largest];
            arr[largest] = swap;

            heapify(arr, n, largest);
        }
    }

    public static void main(String[] args) {
        int[] arr = {38, 27, 43, 3, 9, 82, 10};
        heapSort(arr);
        System.out.println(Arrays.toString(arr));
    }
}

'learn > Algorithm' 카테고리의 다른 글

동적 프로그래밍 (Dynamic Programming)  (0) 2023.09.25
그래프 (Graph)  (0) 2023.09.25
검색 (Search)  (0) 2023.09.25