import java.util.Scanner;
public class Sort {
public void Countsort(int a[], int b[], int k) throws ArrayIndexOutOfBoundsException {
int[] c = new int[k + 1];
for (int i = 0; i < k; i++) {
c[i] = 0;
}
for (int i = 0; i <= a.length; i++) {
c[a[i]] = c[a[i]] + 1;
}
for (int i = 1; i <= k; i++) {
c[i] = c[i] + c[i - 1];
}
for (int i = a.length; i <= 1; i--) {
b[c[a[i]]] = a[i];
c[a[i]] = c[a[i]] - 1;
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int num;
int[] temp = new int[10000];
int i = 0;
while (sc.hasNextInt()) {
num = sc.nextInt();
temp[i] = num;
i++;
if (num == -1) {
break;
}
}
int A[] = new int[i];
// just a check
for (i = 0; i < temp.length; i++) {
System.out.println("temp values:" + temp[i]);
}
// just a check ends
for (int j = 0; j < A.length; j++) {
A[j] = temp[j];
System.out.println("tem copied vals:" + A[j]);
}
// a check for gthat a has temp values..
int[] B = new int[A.length];
new Sort().Countsort(A, B, 100);
for (i = 0; i < B.length; i++) {
System.out.println("Run count #" + i + " : " + B[i]);
}
}
}
Asked
Active
Viewed 316 times
-2

G. Bach
- 3,869
- 2
- 25
- 46
-
2Look at the upper bound and array access of `a` here: `for(int i=0;i<=a.length;i++){ c[a[i]]=c[a[i]]+1;` (That may not be the only problem, but it's certainly one of them...) – Jon Skeet Apr 11 '15 at 14:00
-
Please specify your input. – Spikatrix Apr 11 '15 at 14:01
-
2This code is very unreadable. – Bubletan Apr 11 '15 at 14:02
-
`for(int i=a.length;i<=1;i--)` looks very wrong. Perhaps you wanted `for(int i=a.length;i>=1;i--)`? – Spikatrix Apr 11 '15 at 14:02
-
This is a certain way of causing index out of bound exception: `for(int i=0;i<=a.length;i++)`. It needs to be `<` or `!=`, but not `<=`. – Sergey Kalinichenko Apr 11 '15 at 14:03
-
1This looks like a bad translation from C. Java `int[]` are initialized to zero automatically. – chrylis -cautiouslyoptimistic- Apr 11 '15 at 14:17
-
Start using an environment that uses some formatting rules so your code doesn't confuse readers (and possibly yourself) due to poor readability. Also, why should `a[i]` contain valid array indices? – G. Bach Apr 11 '15 at 15:38
-
Do not copy Java arrays by hand. – greybeard Apr 11 '15 at 17:49
1 Answers
0
First of all your while loop should be
while (sc.hasNextInt()) {
num = sc.nextInt();
if (num == -1) {
break;
}
// so that you can stop -1 to be stored
temp[i] = num;
i++;
}
Next thing is your loop
for (int i = 0; i < a.length; i++) { // always less than length of the array
c[a[i]] = c[a[i]] + 1;
}

AJ.
- 4,526
- 5
- 29
- 41