"C++ 기수정렬 구현"의 두 판 사이의 차이

2번째 줄: 2번째 줄:
;C++ 기수정렬 구현
;C++ 기수정렬 구현
<source lang='cpp'>
<source lang='cpp'>
#include<iostream>
#include <iostream>
using namespace std;
void radix_counting_sort(int a[], int size, int ex, int base) {
void count_sort(int arr[], int size, int exp) {
int i, j, output[size], count[base] = {0};
int i, index, output[size], count[10] = {0};
for(i=0; i<size; i++) count[(a[i]/ex)%base]++;
for(i=0; i<size; i++) count[(arr[i]/exp)%10]++;
for(i=1; i<base; i++) count[i] += count[i-1];
for(i=1; i<10; i++) count[i] += count[i-1];
for(i=size-1; i>-1; i--) {
for(i=size-1; i>-1; i--) {
index = arr[i]/exp;
j = (a[i]/ex)%base;
output[count[index%10]-1] = arr[i];
output[count[j]-1] = a[i];
count[index%10]--;
count[j]--;
}
}
for(i=0; i<size; i++) arr[i] = output[i];
for(i=0; i<size; i++) a[i] = output[i];
}
}
void radix_sort(int arr[], int size) {
void radix_sort(int a[], int size, int base) {
int max = arr[0];
int max = a[0];
for(int i=1; i<size; i++) if(arr[i]>max) max=arr[i];
for(int i=1; i<size; i++) if(a[i]>max) max=a[i];
for(int exp=1; max/exp>0; exp*=10) count_sort(arr, size, exp);
for(int ex=1; max/ex>0; ex*=base) radix_counting_sort(a, size, ex, base);
}
void radix_sort(int a[], int size) {
    radix_sort(a, size, 10);
}
}
int main() {
int main() {
int arr[] = {3,4,2,1,7,5,8,9,0,6,100,10};
int arr[] = {9,1,22,4,0,1,22,100,10};
int size = sizeof(arr)/sizeof(arr[0]);
radix_sort(arr, sizeof(arr)/sizeof(int));
radix_sort(arr, size);
for(int x: arr) std::cout << x << " ";
for(int i=0; i<size; i++) cout << arr[i] << " ";
// 0 1 1 4 9 10 22 22 100  
// 0 1 2 3 4 5 6 7 8 9 10 100  
}
}
</source>
</source>

2018년 8월 27일 (월) 17:43 판

1 개요

C++ 기수정렬 구현
#include <iostream>
void radix_counting_sort(int a[], int size, int ex, int base) {
	int i, j, output[size], count[base] = {0};
	for(i=0; i<size; i++) count[(a[i]/ex)%base]++;
	for(i=1; i<base; i++) count[i] += count[i-1];
	for(i=size-1; i>-1; i--) {
		j = (a[i]/ex)%base;
		output[count[j]-1] = a[i];
		count[j]--;
	}
	for(i=0; i<size; i++) a[i] = output[i];
}
void radix_sort(int a[], int size, int base) {
	int max = a[0];
	for(int i=1; i<size; i++) if(a[i]>max) max=a[i];	
	for(int ex=1; max/ex>0; ex*=base) radix_counting_sort(a, size, ex, base);
}
void radix_sort(int a[], int size) {
    radix_sort(a, size, 10);
}
int main() {
	int arr[] = {9,1,22,4,0,1,22,100,10};
	radix_sort(arr, sizeof(arr)/sizeof(int));
	for(int x: arr) std::cout << x << " ";
	// 0 1 1 4 9 10 22 22 100 
}

2 같이 보기

문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}