c# - Count Sort Algorithm, Unable to sort Perfectally -
i been trying implement count sort algorithm
.
every time run algorithm gives me wrong answer @ index 0 , 1
it been continuous 20 hours, , unable track doing wrong...
generated_array 17 88 14 91 151 50 95 175 92 49 116 67 111 195 37 63 144 50 65 90 sorted_array 0 14 17 37 49 50 50 63 65 67 88 90 91 92 95 111 116 144 151 175 generated_array 8 109 33 37 196 156 158 142 52 179 152 182 171 27 54 75 139 193 25 190 sorted_array 0 8 25 27 33 37 52 54 75 109 139 142 152 156 158 171 179 182 190 193 generated_array 51 24 132 150 73 198 111 55 64 145 15 179 117 6 16 120 155 45 52 108 sorted_array 0 198 15 16 24 45 51 52 55 64 73 108 111 117 120 132 145 150 155 179 generated_array 15 119 162 199 104 104 71 69 40 141 50 119 32 6 155 75 150 140 164 6 sorted_array 0 199 6 15 32 40 50 69 71 75 104 104 119 119 140 141 150 155 162 164 generated_array 22 150 91 145 164 151 145 118 123 105 56 78 185 57 114 128 152 20 124 2 sorted_array 0 185 20 22 56 57 78 91 105 114 118 123 124 128 145 145 150 151 152 164 generated_array 132 191 44 185 116 186 107 195 104 55 107 48 45 109 38 76 45 143 31 58 sorted_array 0 195 38 44 45 45 48 55 58 76 104 107 107 109 116 132 143 185 186 191 generated_array 104 139 137 47 22 180 161 170 39 165 12 16 49 177 11 83 30 34 29 61 sorted_array 0 180 12 16 22 29 30 34 39 47 49 61 83 104 137 139 161 165 170 177
here algorithm using:
int[] counting_sort(int[] array, int max) { int no_of_elements = array.length; int[] sorted_array = new int[array.length]; int[] c = new int[max+1]; (int = 0; < max; i++) { c[i] = 0; } (int j = 0; j <no_of_elements; j++) { c[array[j]] = c[array[j]] + 1; } (int = 1; <max; i++) { c[i] = c[i] + c[i - 1]; } (int j = no_of_elements-1; j >= 0; j--) { sorted_array[c[array[j]]] = array[j]; c[array[j]] = c[array[j]] - 1; } return sorted_array; }
try following
i<=max
in 3rd loopsorted_array[c[array[j]]-1] = array[j]
in 4th loop
int[] counting_sort(int[] array, int max) { int no_of_elements = array.length; int[] sorted_array = new int[array.length]; int[] c = new int[max+1]; (int = 0; < max; i++) { c[i] = 0; } (int j = 0; j <no_of_elements; j++) { c[array[j]] = c[array[j]] + 1; } (int = 1; <=max; i++) { c[i] = c[i] + c[i - 1]; } (int j = no_of_elements-1; j >= 0; j--) { sorted_array[c[array[j]]-1] = array[j]; c[array[j]] = c[array[j]] - 1; } return sorted_array; }
Comments
Post a Comment