Aidid kamil
Aidid kamil

Reputation: 3

sorting 2 array the same way

I have two arrays double sales[] and String sales1[] that store the name for the sales. I need to sort sales[] in descending order and sales1[] has to match it, but currently when sales[] are sorted some of the sales1[] don't match.

sales1[]=("kapas","redang","perhentian","tenggol","lang tengah")

here's my code currently

public void sort(double sales[], String sales1[]) {
    int i, j;
    double temp;
    String temp1;

    for (i = 0; i < sales.length; i++) {
        for (j = i + 1; j < sales.length; j++) {
            if (sales[i] < sales[j]) {
                temp1 = sales1[i];
                sales1[i] = sales1[j];
                sales1[j] = temp1;

                temp = sales[i];
                sales[i] = sales[j];
                sales[j] = temp;

            }
        }
    }
}

Upvotes: 0

Views: 88

Answers (1)

Mike Nakis
Mike Nakis

Reputation: 61969

  • You will create a new class Sale implements Comparable<Sale>.

  • This class will have a double member and a String member.

  • You will give those members meaningful names, like amount and name instead of member1 and member2.

  • This class will also contain a CompareTo method to compare one instance with another. It will be implemented by comparing the double member.

  • You will pass your sort() method an array of Sale instead of the individual arrays you are passing it now.

  • Your sort() method will simply consist of one line, which delegates to Arrays.sort() to quick-sort your array instead of rolling your own extremely inefficient bubblesort.

Upvotes: 1

Related Questions