-
[Sort] Selection Sort (선택 정렬)Basic Programming/Algorithm 2018. 12. 11. 18:20
Selection Sort (선택 정렬)
- Python -
def selection_sort(collection):print('----- Selection Sort -----')print('input : ' + str(collection))for i in range(len(collection)-1, 0, -1):pos_max = 0for j in range (1, i+1):if collection[pos_max] < collection[j]:pos_max = jif(pos_max is not i): #if position is same, swap is unnecessarycollection[pos_max], collection[i] = collection[i], collection[pos_max]print(str(len(collection) - i)+ 'th progressing ... ' + str(input))return collectioninput = [3, 8, 6, 5, 4, 2, 1, 7]result = selection_sort(input)print('\nresult : ' + str(result))Result
- Javascript -
function selctionSort(array) {console.log("----- Selection Sort -----");console.log(`input : ${array}`);let input = array;for(let i = input.length - 1; i > 0; i--) {let posMax = 0;for(let j = 1; j <= i; j++) {if(input[j] > input[posMax]) posMax = j;}if(posMax !== i) { // if position is same, swap is unnecessarylet tmp = input[i];input[i] = input[posMax];input[posMax] = tmp;}console.log(`${input.length - i}th progressing ... ${input}`);}return input;}let input = [3, 8, 6, 5, 4, 2, 1, 7];let result = selctionSort(input);console.log(`\nresult : ${result}`);Result
*** if posMax and i are at the same position, swap is unnecessary. but using <if> can make more time complexity.
It depends on the order of data input and size. So it's OK to just remove that <if> statement.
'Basic Programming > Algorithm' 카테고리의 다른 글
[Sort] Insertion Sort (삽입 정렬) (0) 2018.12.10 [Sort] Bubble Sort (버블 정렬, 거품 정렬) (0) 2018.12.10