Back to Home

ការតម្រៀបបែបរាប់

ក្បួនដោះស្រាយតម្រៀបមិនប្រៀបធៀបដែលដំណើរការដោយរាប់ចំនួនធាតុដែលមានតម្លៃគន្លឹះខុសៗគ្នា។

Visualization

Step 1 / 11
Speed:

Details

Analogy

ស្រមៃថាអ្នកមានបំពង់ធំមួយដែលមានគ្រាប់ក្រឡាច្រើនពណ៌ (ក្រហម ខៀវ បៃតង)។ ដើម្បីតម្រៀបវា អ្នកត្រូវមានធុងសម្រាប់ពណ៌នីមួយៗ។ អ្នកយកគ្រាប់ក្រឡាទាំងអស់មួយមួយទៅដាក់ក្នុងធុងតាមពណ៌របស់វា។ បន្ទាប់មក អ្នកគ្រាន់តែយកគ្រាប់ក្រឡាចេញពីធុងតាមលំដាប់ (ក្រហមទាំងអស់ បន្ទាប់មកខៀវ...) ដើម្បីទទួលបានអារេដែលបានតម្រៀប។

Purpose

ដើម្បីតម្រៀបធាតុអារេប្រកបដោយប្រសិទ្ធភាព នៅពេលធាតុជាចំនួនគត់ក្នុងជួរតូចដែលបានកំណត់។

Use Cases

មានប្រសិទ្ធភាពសម្រាប់តម្រៀបចំនួនគត់ដែលមានជួរតូច។ ប្រើជាជំនួយក្នុង Radix Sort។ មិនសមស្របសម្រាប់ជួរធំ។

Algorithm Steps

Line 1
1
find max value in arr
2
create count array of size max+1
3
for each element in arr:
4
count[element]++
5
for i = 1 to max:
6
count[i] += count[i-1]
7
create output array
8
for i = n-1 to 0:
9
output[count[arr[i]]-1] = arr[i]
10
count[arr[i]]--
11
copy output to arr
Current
Executed
Pending

Explanation

What's Happening?

Step 1/11

អារេដំបូង: [4, 2, 2, 3, 3, 8, 1]។ តម្លៃអតិបរមាគឺ 8។

Updates with each step • Clickfor full view

Code Implementation

def counting_sort(arr):
    max_val = max(arr)
    count = [0] * (max_val + 1)
    output = [0] * len(arr)

    for i in arr:
        count[i] += 1

    for i in range(1, max_val + 1):
        count[i] += count[i - 1]

    for i in range(len(arr) - 1, -1, -1):
        output[count[arr[i]] - 1] = arr[i]
        count[arr[i]] -= 1

    return output
ការតម្រៀបបែបរាប់ - Interactive Visualization | AlgoViz | AlgoViz