Spartan-196 Spartan-196 - 5 months ago 9
Java Question

Java Sort multiple arrays based of another array

I am looking to do an ascending sort 7 arrays, based of a the values of one of them and then print the final array using a loop inside of a method. the array values are entered by the user and will contain at least one set of data but no more than 5 sets.

My code so far is below, its the basic structure of a selection sort as I was requested to use that, I am looking to do the ascending sort off of the array simp (stands for simple interest) but I cannot figure out how to get all the other arrays to move with it retain the values.

any ideas on the loop method to use for this?

public static void sort(double[] amount, double[] iRate, int[] term, double[] simp, double[] month, double[] daily, double[] weekly)
{

for (int i=0;i<simp.length-1;i++)
{
int minindex=i;
for (int j=i+1;j<simp.length;j++)
{
if(simp[minindex]>simp[j])
minindex=j;
}
double temp = simp[minindex];
simp[minindex]=simp[i];
simp[i]= temp;
}

}


Example Run

[Line #] [Principal Amount] Interest rate term simple monthly weekly daily
1 $1,375.00 1.18% 7 9.4244 9.4522 9.4557 9.4567
2 $100.00 3.25% 6 1.625 1.636 1.6377 1.6382
3 $100.00 3.25% 12 3.25 3.2988 3.3023 3.3032

[Line #] [Principal Amount] Interest rate term simple monthly weekly daily
1 $100.00 3.25% 6 1.62 1.636 1.6377 1.6382
2 $100.00 3.25% 12 3.25 3.2988 3.3023 3.3032
3 $1,375.00 1.18% 7 9.4244 9.4522 9.4557 9.4567

Answer

One straightforward way to do it using your existing code is to swap elements in all arrays whenever you are swapping elements in simp:

double temp = simp[minindex];
simp[minindex]=simp[i];
simp[i]= temp;

temp = iRate[minindex];
iRate[minindex]=iRate[i];
iRate[i]= temp;

.
.
.

This isn't the most elegant way. The OO way to do it would be to have an object that has amount, iRate, term... as members and sort an array of these objects.