ការតម្រៀបបែបឫស
ក្បួនដោះស្រាយការតម្រៀបមិនប្រៀបធៀប ដែលតម្រៀបចំនួនគត់ដោយដំណើរការខ្ទង់នីមួយៗ។
Visualization
Details
Analogy
ลองนึกภาพการเรียงลำดับรายการคำตามตัวอักษรโดยไม่ต้องเปรียบเทียบโดยตรง ขั้นแรกคุณจะต้องจัดเรียงคำทั้งหมดลงใน 26 ถังตามตัวอักษรตัวสุดท้าย จากนั้นคุณจะต้องรวบรวมคำเหล่านั้นอีกครั้งแล้วจัดเรียงลงในถังตามตัวอักษรตัวที่สองจากท้ายสุดไปเรื่อยๆ จนกว่าจะถึงตัวอักษรตัวแรก หลังจากผ่านรอบสุดท้ายแล้ว รายการคำทั้งหมดจะถูกจัดเรียงอย่างสมบูรณ์
Purpose
เพื่อจัดเรียงจำนวนเต็มโดยการจัดกลุ่มคีย์ตามตัวเลขแต่ละตัวซึ่งมีตำแหน่งและค่าสำคัญเหมือนกัน มันประมวลผลตัวเลขจากเลขนัยสำคัญน้อยที่สุดไปยังเลขนัยสำคัญมากที่สุด
Use Cases
មានប្រសិទ្ធភាពខ្ពស់សម្រាប់ការតម្រៀបសំណុំលេខពេញធំឬសោខ្សែអក្សរ។ ដោយសារវាមិនផ្អែកលើការប្រៀបធៀប វាអាចលឿនជាងក្បួនដោះស្រាយតម្រៀប O(n log n)។
Algorithm Steps
find max value in arr
exp = 1
while max / exp > 0:
countingSort(arr, exp)
exp *= 10
function countingSort(arr, exp):
create output and count arrays
count occurrences of digits at exp position
convert count to cumulative count
build output array from right to left
copy output back to arr
Explanation
What's Happening?
អារេដែលមិនបានតម្រៀបដំបូង។
Code Implementation
def radix_sort(arr):
max_val = max(arr)
exp = 1
while max_val // exp > 0:
counting_sort_for_radix(arr, exp)
exp *= 10
return arr
def counting_sort_for_radix(arr, exp):
n = len(arr)
output = [0] * n
count = [0] * 10
for i in range(n):
index = arr[i] // exp
count[index % 10] += 1
for i in range(1, 10):
count[i] += count[i - 1]
i = n - 1
while i >= 0:
index = arr[i] // exp
output[count[index % 10] - 1] = arr[i]
count[index % 10] -= 1
i -= 1
for i in range(n):
arr[i] = output[i]