Basic Programming/Algorithm

[Sort] Insertion Sort (삽입 정렬)

지로원 2018. 12. 10. 18:49

Insertion Sort (삽입 정렬)


- Python -


def insertion_sort(collection):
print('----- Insertion Sort -----')
print('input : ' + str(collection))

for i in range(1, len(collection)):
while 0 < i and collection[i] < collection[i-1]:
collection[i], collection[i-1] = collection[i-1], collection[i]
i = i - 1
print('progressing ... ' + str(collection))

return collection

input = [3, 1, 6, 8, 4, 2, 9, 7, 10, 5]

result = insertion_sort(input)
print('\nresult : ' + str(result))


Result



-Javascript-


function insertionSort(array) {
console.log("----- Insertion Sort -----");
console.log(`input : ${array}`);
let input = array;

let tmp;
for(let i = 1; i < input.length; i++) {
let j = i;
while (input[j] < input[j - 1]) {
tmp = input[j - 1];
input[j - 1] = input[j];
input[j] = tmp;
j -= 1;
}
console.log(`${i}th progressing ... ${input}`);
}
return input;
}

let input = [3, 8, 6, 5, 4, 2, 1, 7];
let result = insertionSort(input);

console.log(`\nresult : ${result}`);


Result




( 설명 추가 예정 )