π 2023λ 12μ 28μΌ
[μκ³ λ¦¬μ¦ 1μΌμ°¨]
ν μ λ ¬(heap sort)λ ν(heap)μ μ¬μ©νμ¬ μ λ ¬νλ μκ³ λ¦¬μ¦μ΄λ€.
νμ "λΆλͺ¨μ κ°μ΄ μμμ κ°λ³΄λ€ νμ ν¬λ€ or μλ€"λΌλ 쑰건μ λ§μ‘±νλ μμ μ΄μ§νΈλ¦¬.
μ₯μ
λΉ λ₯΄λ€.
μΆκ°μ μΈ λ°°μ΄μ΄ νμνμ§ μλ€.
λ¨μ
ν΅μ΄ νκ· μ μΌλ‘ λ λΉ λ₯΄λ€.
λΆμμ μ λ ¬μ΄λ€.
public static void main(String[] args) { int[] HeapArr = {7,6,5,8,3,5,9,1,7}; // μ΅μ νκ΅¬μ± : n/2λ²λ§νΌ heapify μν for(int i = HeapArr.length/2-1; i>=0; i--){ heapify(HeapArr, i, HeapArr.length); } System.out.println(Arrays.toString(HeapArr)); // μ΅μ΄ νκ΅¬μ± μ΄νμ root λ Έλμ λ§μ§λ§ λ Έλμ change for(int i =HeapArr.length-1; i>0; i--){ swap(HeapArr, 0, i); heapify(HeapArr, 0, i); } System.out.println(Arrays.toString(HeapArr)); }
static void heapify( int[] HeapArr, int root, int arr_size){ int left = 2 * root + 1; int right = 2 * root + 2; int temp = root; if(left<arr_size && HeapArr[left] > HeapArr[temp]){ temp = left; } if(right<arr_size && HeapArr[right] > HeapArr[temp]){ temp = right; } if(temp != root){ swap(HeapArr, root, temp); heapify(HeapArr, temp, arr_size); } } static void swap(int[] HeapArr, int x, int y){ int num = HeapArr[x]; HeapArr[x] = HeapArr[y]; HeapArr[y] = num; }
νλ‘κ·Έλλ¨Έμ€ λ¬Έμ : λ 맡κ²
νλ‘κ·Έλλ¨Έμ€ λ¬Έμ : λμ€ν¬ 컨νΈλ‘€λ¬
νλ‘κ·Έλλ¨Έμ€ λ¬Έμ : μ΄μ€ μ°μ μμν
public class DFS_ListGraph { static List<List<Integer>> list = new ArrayList<>(); static boolean[] visited; public static void main(String[] args) { int [][] input = { {0,1}, {0,2}, {1,3}, {2,3}, {2,4}, }; visited = new boolean[input.length]; for(int i = 0; i<input.length; i++){ list.add(new ArrayList<>()); } for (int[] a : input ){ addEdge(a[0],a[1]); } System.out.println(list); System.out.println(); dfs(1); } static void addEdge(int a , int b){ list.get(a).add(b); list.get(b).add(a); } static void dfs(int start) { System.out.println(start); visited[start] = true; for (int i = 0; i<list.get(start).size(); i++) { if(!visited[list.get(start).get(i)]) { dfs(list.get(start).get(i)); } } } }
public class DFS_ArrayGraph { static int[][] graph; static boolean[] visited; public static void main(String[] args) { graph = new int[][]{ {0, 1, 1, 0, 0}, {1, 0, 0, 1, 0}, {1, 0, 0, 1, 1}, {0, 1, 1, 0, 0}, {0, 0, 1, 0, 0} }; visited = new boolean[graph.length]; dfs( 0); } static void dfs(int start) { System.out.println(start); visited[start] = true; for (int i = 0; i<graph[start].length; i++) { if(!visited[i] && graph[start][i] == 1) { dfs(i); } } } }
νλ‘κ·Έλλ¨Έμ€ λ¬Έμ : λ€νΈμν¬
νλ‘κ·Έλλ¨Έμ€ λ¬Έμ : νκ² λλ²