Reputation: 87
I posted a question yesterday regarding the sorting of indexes in an array. I was getting weird results, which were partly correct. I figured out the reason, but I don't know how to fix it.
I've declared an array to have a MAX number of indexes of 50. After reading data into a file, only 24 or so are filled with actual data, the rest are filled with 0's. When I go to print, all 50 indexes are listed, in ascending order. I can't figure out how to only print the indexes with data.
Here is the link to my question yesterday: Sorting double arrays into ascending order
Below is my code to the array declaration and initialization, sort loop, and printing. Any help would be great!
private double[] x;
x = new double[50];
int index, j = x.length - 1,double temp;
for (j = x.length - 1; j >= 0; j--) {
for (index = 0; index <= j - 1; index++) { //start for
if (x[index] > x[index + 1]) { //start if
temp = x[index];
x[index] = x[index + 1];
x[index + 1] = temp;
}
}
}
for (index = 0; index < x.length; index++) {
System.out.printf("%3d. \t\t%5.1f%%\n", (index + 1), x[index]);
}
Upvotes: 0
Views: 814
Reputation: 150
Since all array indexes are initialized to 0, your sort algorithm will move all the indexes without data (basically 0s) to the front of the array, before the values you added-- which as pointed out, may also contain 0s. Then, your print method prints the entire array, since you're starting from index=0
and moving all the way up to the end of the array.
I suggest the following: when adding data to the array, keep a count
variable that keeps track of how many values you've added (i.e. do count++
every time a new value is added), then sort the array.
Then print like this:
for (index = x.length-count; index < x.length; index++) {
System.out.printf("%3d. \t\t%5.1f%%\n", (index + 1), x[index]);
}
Thus, you're printing out only the data that you've added yourself, and not the empty indexes.
Upvotes: 1
Reputation: 52185
I see two options:
You can use an ArrayList. This is a dynamic data structure which will keep on increasing in size the more items you throw in it. When you are done, you just iterate over the ArrayList and print its content. OR
When populating the array, you keep track of how many items you have actually added. You then iterate from 0 to this number, instead of the size of the entire array.
Upvotes: 1
Reputation: 6618
Use an ArrayList
instead of an array. That keeps track of the added items so that you do not need to reinvent the standard library. If you really need to use an array, then keep the count of items and print only the amount of items you have.
Upvotes: 1