arr[8] (3) => countArr[3] (7)
countArr[3] (7) => resultArr[7] (3)
countArr[3]--
Stable 정렬 알고리즘
입력한 동일한 값이 있을 때 입력에서 먼저 나오는 값이 출력에서도 먼저 나온다
function coutingSort(arr, k) {
const countArr = new Array(k + 1).fill(0)
arr.forEach(item => {
countArr[item]++
})
console.log(countArr); // [2, 0, 2, 3, 0, 1]
for (let i = 1; i < countArr.length; i++) {
countArr[i] = countArr[i] + countArr[i - 1]
}
console.log(countArr); // [2, 2, 4, 7, 7, 8]
const result = []
for (let j = arr.length - 1; j >= 0; j--) {
const index = arr[j] // 0
// resultArr가 0부터 시작하기 때문에 -1 추가 필요
result[countArr[index] - 1] = index
countArr[index]--
}
return result
}
const arr = [2, 5, 3, 0, 2, 3, 0, 3]
const k = 5
console.log(coutingSort(arr, k)) // [0, 0, 2, 2, 3, 3, 3, 5]
function radixSort(arr, k, d) {
let radix = d - 1
const result = []
while (radix >= 0) {
const countArr = new Array(k + 1).fill(0)
arr.forEach(item => {
const str = item + ''
countArr[+str[radix]]++
})
console.log('1', countArr);
for (let i = 1; i < countArr.length; i++) {
countArr[i] = countArr[i] + countArr[i - 1]
}
console.log('2', countArr);
for (let j = arr.length - 1; j >= 0; j--) {
const value = arr[j] + ""
const radixValue = +value[radix]
const index = countArr[radixValue]
result[index - 1] = +value
countArr[radixValue]--
}
radix--
console.log('3', result);
console.log("==========================================");
}
return result
}
const arr = [329, 457, 657, 839, 436, 720, 355]
const k = 9
const d = 3
console.log(radixSort(arr, k, d));
function radixSort(arr, k, d) {
let radix = 1
const result = []
while (radix <= d) {
const countArr = new Array(k + 1).fill(0)
arr.forEach(item => {
const radixValue = getRadixValue(item, radix)
countArr[radixValue]++
})
console.log('1', countArr);
for (let i = 1; i < countArr.length; i++) {
countArr[i] = countArr[i] + countArr[i - 1]
}
console.log('2', countArr);
for (let j = arr.length - 1; j >= 0; j--) {
const value = arr[j]
const radixValue = getRadixValue(value, radix)
const index = countArr[radixValue]
result[index - 1] = +value
countArr[radixValue]--
}
radix++
console.log('3', result);
console.log("==========================================");
}
return result
}
function getRadixValue(item, radix) {
return Math.floor((item % Math.pow(10, radix)) / Math.pow(10, radix - 1))
}
const arr = [329, 457, 657, 839, 436, 720, 355]
const k = 9
const d = 3
console.log(radixSort(arr, k, d));
// 1의 자리 수 정렬
1(10)[1, 0, 0, 0, 0, 1, 1, 2, 0, 2]
2(10)[1, 1, 1, 1, 1, 2, 3, 5, 5, 7]
3(7)[720, 355, 436, 457, 657, 329, 839]
==========================================
1(10)[0, 0, 2, 2, 0, 3, 0, 0, 0, 0]
2(10)[0, 0, 2, 4, 4, 7, 7, 7, 7, 7]
3(7)[329, 720, 839, 436, 457, 657, 355]
==========================================
1(10)[0, 0, 0, 2, 2, 0, 1, 1, 1, 0]
2(10)[0, 0, 0, 2, 4, 4, 5, 6, 7, 7]
3(7)[329, 355, 457, 436, 657, 720, 839]
==========================================
(7)[329, 355, 457, 436, 657, 720, 839]
Photo by Michael Dziedzic on Unsplash
텍스트