Im trying to bucket sort an array and represent the sorting visually with processing functions.
Found this bucket sort code to be rather common used in Java:
import java.util.*;
import java.util.Collections;
float[] arr = {23, 4, 67, 1, 90, 54, 21, 50};
int pos1 = -1, pos2 = -1;
void setup()
{
size(600,600);
background(255);
thread("Execute");
}
void Execute()
{
delay(1000);
BucketSort(arr, arr.length);
}
void draw()
{
background(255);
int N = arr.length;
float base = width/N;
for(int i = 0; i < N; i++)
{
if(i >= pos1 && i <= pos2) fill(0, 0, 255);
else fill(0, 255, 0);
float h = arr[i] * 5;
rect(i*base, height - h, base, h);
}
}
void BucketSort(float arr[], int n)
{
if (n <= 0) return;
Vector<Float>[] buckets = new Vector[n];
for (int i = 0; i < n; i++) {
buckets[i] = new Vector<Float>();
}
for (int i = 0; i < n; i++) {
float idx = arr[i] * n;
buckets[(int)idx].add(arr[i]);
}
for (int i = 0; i < n; i++) {
Collections.sort(buckets[i]);
}
int index = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < buckets[i].size(); j++) {
arr[index++] = buckets[i].get(j);
}
}
}
but its giving away those errors:
java.lang.ArrayIndexOutOfBoundsException: 184
at aula8.BucketSort(aula8.java:63)
at aula8.Execute(aula8.java:34)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at processing.core.PApplet.method(PApplet.java:3867)
at processing.core.PApplet$2.run(PApplet.java:3905)
can someone explain it to me? im kinda noob in java and processing, it looks like the code is trying to access a number in the array that is out of its bounds, <0 or >8, but I dont understand where the code is trying it.