In this HackerRank Counting Sort 2 problem you have Given an unsorted list of integers, use the counting sort method to sort the list, and then print the sorted list.
Problem solution in Python programming.
n = int( input() ) ar = [ int(v) for v in input().split() ] count = [0]*100 for item in ar: count[item] += 1 for i in range(100): if count[i] > 0: print( " ".join( [str(i)]*count[i] ), end=" " )
Problem solution in Java Programming.
import java.io.*; import java.util.*; public class Solution { public static int[] count(int[] ar, int max){ int[] counts = new int[max+1]; for(Integer n : ar){ counts[n] += 1; } return counts; } public static void printCount(int[] counts){ for(int i = 0; i < counts.length; ++i){ for(int j = 0; j < counts[i]; ++j){ System.out.print(i + " "); } } System.out.println(); } public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int[] ar = new int[n]; for(int i=0;i<n;i++){ ar[i]=in.nextInt(); } int[] counts = count(ar, 99); // printArray(counts); printCount(counts); } }
Problem solution in C++ programming.
#include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> using namespace std; int main() { int n; cin>>n; const int LEN = 100; int dic[LEN] = {0}; for(int i=0; i<n; i++){ int tmp; cin >> tmp; dic[tmp]++; } for(int i=0; i<LEN; i++){ for(int j=0; j<dic[i]; j++){ cout<< i << " "; } } return 0; }
Problem solution in C programming.
#include <stdio.h> #include <string.h> #include <math.h> #include <stdlib.h> int main() { int n; scanf("%d", &n); int ar1 [n]; for (int i = 0; i < n; i++) { scanf("%d", ar1 + i); } int ar2 [100]; for (int j = 0; j < 100; j++) { ar2[j] = 0; } count(ar1, ar2, n); for(int k = 0; k < 100; k++) { int c = ar2[k]; while(c > 0) { printf("%d ", k); c--; } } return 0; } void count (int* ar1, int *ar2, int size) { for(int i = 0; i < size; i++) { ar2[(ar1[i])]++; } }
Problem solution in JavaScript programming.
process.stdin.resume(); process.stdin.setEncoding('ascii'); var input = ""; process.stdin.on('data', function (data) { input += data; }); function sortNumber(a,b) { return a - b; } function write(text){ process.stdout.write(""+text+"n"); } process.stdin.on('end', function () { input = input.split("n"); var array = input[1].split(" "); for(var a = 0; a < array.length; a++){ array[a] = parseInt(array[a]); } var ret = array.sort(sortNumber).join(" "); write(ret); });