Insert Sort Bubble Sort - accidentlywoo/legacyVue GitHub Wiki
Insert Sort / Bubble Sort
1. Insertion Sort
Space - Complexity = In - Place Sort : O(1)์ ๋ณด์กฐ ๋ฉ๋ชจ๋ฆฌ๋ฅผ ์ฌ์ฉํ๋ค. Time - Complexity = O(n^2)
์๋ฆฌ
n๊ฐ์ ์์๋ฅผ ๊ฐ์ง ๋ฐฐ์ด์ ์ ๋ ฌํ ๋, i๋ฒ์งธ๋ฅผ ์ ๋ ฌ ์์๋ผ๊ณ ๊ฐ์ ํ๋ฉด,0๋ถํฐ i-1๊น์ง์ ์์๋ค์ ์ ๋ ฌ๋์ด์๋ค๋ ๊ฐ์ ํ์, i๋ฒ์งธ ์์๋กธ i-1 ๋ฒ์งธ ์์๋ถํฐ 0๋ฒ์งธ ์์๊น์ง ๋น๊ตํ๋ฉด์ i๋ฒ์งธ ์์๊ฐ ๋น๊ตํ๋ ์์๋ณด๋ค ํด ๊ฒฝ์ฐ ์๋ก์ ์์น๋ฅผ ๋ฐ๊พธ๊ณ , ์์ ๊ฒฝ์ฐ ์์น๋ฅผ ๋ฐ๊พธ์ง ์๊ณ ๋ค์ ์์(i+1)์ ์์์ ๋น๊ตํ๋ฉด์ ์ ๋ ฌํด์ค๋ค. ์ด ๊ณผ์ ์ ์ ๋ ฌํ๋ ค๋ ๋ฐฐ์ด์ ๋ง์ง๋ง ์์๊น์ง ๋ฐ๋ณตํด์ค๋ค.
C code ` void insertion_sort(int*arr,int size){ int temp; int j;
for(int i = 1;i < size; i++){ temp = arr[i]; for(j = 1-1; j >=0; j--){ if(temp < arr[j]){ arr[j + 1] = arr[j]; }else{ break; } } arr[j + 1] = temp; } } `
2. Bubble Sort
Space - Complexity = In-place Sort:O(1)์ ๋ณด์กฐ ๋ฉ๋ชจ๋ฆฌ๋ฅผ ์ฌ์ฉํ๋ค. Time - Complexity = O(n^2)
์๋ฆฌ
์ธ์ ํ ๋ ๊ฐ์ ๋ฐ์ดํฐ๋ฅผ ๋น๊ตํด๊ฐ๋ฉด์ ์ ๋ ฌ์ ์งํํ๋ ๋ฐฉ์์ด๋ค. ๊ฐ์ฅ ํฐ ๊ฐ์ ๋ฐฐ์ด์ ๋งจ ๋์๋ค ์ด๋์ํค๋ฉด์ n๋ฒ์ ๋ ๋ฒ ๋ฐ๋ณตํ๊ฒ ๋๋ค.
C Code ` void bubble_sort(int*arr, int size){ for(int j = 0; j < size -1; j++){ for(int i = 0; i < (size-j)-1;i++){ if(arr[i] > arr[i+1]){ swapValue(&arr[i], &arr[i+1}); } } } }
//util - swap void swapValue(int *a,int *b){ int temp = *a; *a = *b; *b = temp; } ` ์๋ฐ์ฝ๋๋ก ์ง๋ณด์!