계수 정렬은 비 비교 정렬 알고리즘입니다. 각 고유 요소의 발생 횟수를 계산하여 배열을 정렬합니다. 고유 한 요소의 개수를 부분적으로 해시 한 다음 계산을 수행하여 정렬 된 최종 배열에서 각 요소의 인덱스를 찾습니다. 상당히 빠른 알고리즘이지만 대규모 데이터 세트에는 적합하지 않습니다. 기수 정렬 내에서 서브 루틴으로 사용됩니다.
++ cCopy#include<iostream>
using namespace std;constint N =10;intmaxm(int arr[],int n){int max = arr[0];for(int i =1; i < n; i++){if(arr[i]> max){
max = arr[i];}}return max;}intminm(int arr[],int n){int min = arr[0];for(int i =1; i < n; i++){if(arr[i]< min){
min = arr[i];}}return min;}voidcountingSort(int arr[],int n){int min =minm(arr, n);int max =maxm(arr, n);int range = max - min +1;int count[range]={};int output[n];for(int i =0; i < n; i++) count[arr[i]- min]++;for(int i =1; i < range; i++) count[i]+= count[i -1];for(int i = n -1; i >=0; i--){
output[count[arr[i]- min]-1]= arr[i];
count[arr[i]- min]--;}for(int i =0; i < n; i++) arr[i]= output[i];}intmain(){int n =7;int arr[7]={3,5,1,1,4,2,1};
cout <<"Input arr: ";for(int i =0; i < n; i++){
cout << arr[i]<<" ";}
cout <<"\n";countingSort(arr, n);// Sort elements in ascending order
cout <<"Output arr: ";for(int i =0; i < n; i++){
cout << arr[i]<<" ";}
cout <<"\n";}
Harshit Jindal has done his Bachelors in Computer Science Engineering(2021) from DTU. He has always been a problem solver and now turned that into his profession. Currently working at M365 Cloud Security team(Torus) on Cloud Security Services and Datacenter Buildout Automation.