Advertisement
Guest User

A1

a guest
Feb 18th, 2020
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.48 KB | None | 0 0
  1. public static int[] countingSort(int[] a) {
  2.  
  3. if (a.length == 0) {
  4.  
  5. return a;
  6. }
  7.  
  8. int max = a[0];
  9.  
  10. for (int i = 1; i < a.length; i++)
  11.  
  12. if (a[i] > max)
  13.  
  14. max = a[i];
  15.  
  16. int[] sorted = new int[a.length];
  17.  
  18. int[] count = new int[max > a.length ? max + 1: a.length + 1];
  19.  
  20. for (int element = 0; element < a.length; element++)
  21.  
  22. count[a[element]]++;
  23.  
  24. for (int i = 0, j = 0; i < count.length; i++) {
  25.  
  26. while (count[i] != 0) {
  27.  
  28. sorted[j] = i;
  29.  
  30. count[i]--;
  31.  
  32. j++;
  33. }
  34. }
  35.  
  36. return sorted; // return an array with sorted values
  37. }
  38.  
  39. /*
  40. * This method makes a list of integers between 0-524287
  41. * The sorting method used is Radix Sort
  42. */
  43. public static int[] radixSort(int[] a) {
  44.  
  45. if (a.length == 0) {
  46.  
  47. return a;
  48. }
  49.  
  50. int max = a[0];
  51.  
  52. for (int i = 1; i < a.length; i++) {
  53.  
  54. if (a[i] > max) {
  55.  
  56. max = a[i];
  57. }
  58. }
  59.  
  60. int num = 1;
  61.  
  62. int[] arr2 = new int[1000];
  63.  
  64. while (max / num > 0) {
  65.  
  66. int[] arr = new int[10];
  67.  
  68. for (int i = 0; i < a.length; i++)
  69.  
  70. arr[((a[i] / num) % 10)]++;
  71.  
  72. for (int i = 1; i < arr.length; i++)
  73.  
  74. arr[i] += arr[i - 1];
  75.  
  76. for (int i = a.length - 1; i >= 0; i--)
  77.  
  78. arr2[--arr[(a[i] / num) % 10]] = a[i];
  79.  
  80. for (int i = 0; i < a.length; i++)
  81.  
  82. a[i] = arr2[i];
  83.  
  84. num *= 10;
  85.  
  86. }
  87.  
  88. return a; // return an array with sorted values
  89. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement