Question

I have to key in 7 values, representing a distance. Have to sort with exchange sort in ascending order.

I also set up a parallel array to keep track of the days of the week, so that when you output the sorted data the corresponding weekday is listed.

I can sort the array with no problem, but when I enter the days it will print out in the order I input it, not with the corresponding value. I am not able to figure out how to enter the day with the corresponding value AFTER it gets sorted. I know my logic is off. Thanks in advance!

Sample output:
7 km on Thursday
8 km on Monday
4 km on Tuesday
and so on...

import java.io.*; 
import java.util.*; 
public class exchangeSort
{
public static void main()
{
    Scanner kbReader= new Scanner (System.in);
    double dist []= new double [7];
    String days []= new String [7];

    for (int i=0; i<dist.length; i++)
    {
        System.out.println("Enter distance");
        dist[i]= kbReader.nextDouble();
        System.out.println("Now enter a day");
        days[i]= kbReader.next();
    }
    System.out.println(" ");

    sort (dist);
    for (int i=0; i<days.length; i++)
    {
        System.out.println(dist[i] + " km on " + days[i]);
    }        
}
public static void sort (double num [] )
{
    int i, j; 
    double temp; 
    for ( i=0; i< num.length-1; i++ ) 
    {
        for ( j=i+1; j <num.length; j++ )
        {
            if( num[i] > num[j] ) 
            {
                temp = num[i];
                num[i] = num[j];
                num[j] = temp; 
            } 
        }
    }
} 
}
Was it helpful?

Solution

When you swap the elements of array numbers, swap the elements of array labels also :

public static void sort (double num [], String[] labels )
{
    int i, j; 
    double temp; 
    for ( i=0; i< num.length-1; i++ ) 
    {
        for ( j=i+1; j <num.length; j++ )
        {
            if( num[i] > num[j] ) 
            {
                temp = num[i];
                num[i] = num[j];
                num[j] = temp; 
                // ----------------- here -------------------
                String tmp = labels[i];
                labels[i] = labels[j];
                labels[j] = tmp; 
            } 
        }
    }
} 

Then you can simply pass the days to the sorting function :

sort (dist, days);

OTHER TIPS

Use a Map. That ties the double to the string, and when you sort based on the double, you always get the right day. You can then sort the key set of the Map however you like, though for double, you are best using a TreeSet and Doubles natural ordering.

The nice thing about a Map is that it makes your code more logical, as the doubles and the days really go together conceptually, so they should be stored together in a single data structure, and that will make your code easier to understand.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top