알고리즘/알고리즘
[알고리즘] 기수정렬
2023. 12. 26. 01:22반응형
소스코드 (C++)
#include <iostream>
// Function to find the maximum number to determine the number of digits
int getMax(int arr[], int n) {
int max = arr[0];
for (int i = 1; i < n; i++)
if (arr[i] > max)
max = arr[i];
return max;
}
// Using counting sort to sort elements based on significant places
void countingSort(int arr[], int n, int exp) {
const int BASE = 10;
int* output = new int[n];
int count[BASE] = { 0 };
// Store count of occurrences in count[]
for (int i = 0; i < n; i++)
count[(arr[i] / exp) % BASE]++;
// Change count[i] so that count[i] contains the actual
// position of this digit in output[]
for (int i = 1; i < BASE; i++)
count[i] += count[i - 1];
// Build the output array
for (int i = n - 1; i >= 0; i--) {
output[count[(arr[i] / exp) % BASE] - 1] = arr[i];
count[(arr[i] / exp) % BASE]--;
}
// Copy the output array to arr[], so that arr[] contains
// sorted numbers according to the current digit
for (int i = 0; i < n; i++)
arr[i] = output[i];
}
// Radix Sort function
void radixSort(int arr[], int n) {
// Find the maximum number to determine the number of digits
int max = getMax(arr, n);
// Do counting sort for every digit
for (int exp = 1; max / exp > 0; exp *= 10)
countingSort(arr, n, exp);
}
// Utility function to print an array
void printArray(int arr[], int n) {
for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
printf("\n");
}
// Driver program to test above functions
int main() {
int arr[] = { 170, 45, 75, 90, 802, 24, 2, 66 };
int n = sizeof(arr) / sizeof(arr[0]);
printf("Given array is \n");
printArray(arr, n);
// Perform radix sort
radixSort(arr, n);
printf("\nSorted array is \n");
printArray(arr, n);
return 0;
}
실행화면
Given array is 170 45 75 90 802 24 2 66 Sorted array is 2 24 45 66 75 90 170 802 |
반응형
'알고리즘 > 알고리즘' 카테고리의 다른 글
[알고리즘] 병합정렬 (Merge sort) (0) | 2024.12.05 |
---|---|
[알고리즘] BFS/DFS 의사코드 (0) | 2022.11.27 |
재귀 함수 쉽게 이해하기 및 예시 (2) | 2022.03.08 |
[알고리즘] 자바 기본 입출력하기 (코딩테스트 전용, 코테전용) (0) | 2022.01.19 |