fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone
  9. {
  10.  
  11. public static int[] sort(int ... unsorted) {
  12. if (null == unsorted || unsorted.length < 2) {
  13. return unsorted; // nothing to sort
  14. }
  15. // 1, 2. Find min and max
  16. int max = unsorted[0];
  17. int min = unsorted[0];
  18.  
  19. for (int i = 1; i < unsorted.length; i++) {
  20. if (min > unsorted[i]) {
  21. min = unsorted[i];
  22. } else if (max < unsorted[i]) {
  23. max = unsorted[i];
  24. }
  25. }
  26.  
  27. // 3. New array to store frequencies
  28. int[] freq = new int[max - min + 1];
  29.  
  30. // 4. Count frequencies shifting by min elements
  31. for (int i = 0; i < unsorted.length; i++) {
  32. freq[unsorted[i] - min] += 1; // shift by min
  33. }
  34.  
  35. // 5,6.Create and populate sorted array
  36. int[] sorted = new int[unsorted.length];
  37.  
  38. for (int i = 0, ix = 0; i < freq.length; i++) {
  39. if (freq[i] == 0) {
  40. continue; // skip values with 0 frequency
  41. }
  42. while (freq[i] > 0) {
  43. sorted[ix++] = min + i; // populate sorted array
  44. freq[i]--;
  45. }
  46. }
  47.  
  48. return sorted;
  49. }
  50.  
  51. public static void main (String[] args) throws java.lang.Exception
  52. {
  53. System.out.println(Arrays.toString(sort(1, 4, -2, 4, 2, 0, -1, 2)));
  54. }
  55. }
Success #stdin #stdout 0.09s 32512KB
stdin
Standard input is empty
stdout
[-2, -1, 0, 1, 2, 2, 4, 4]