1 Replies - 1763 Views - Last Post: 04 April 2011 - 08:45 PM Rate Topic: -----

#1 Shevanel  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 22
  • Joined: 21-November 10

Sorting 2D Array with Selection Sort

Posted 04 April 2011 - 07:07 PM

Hello guys! I'm trying to read some info from a file, and I need to sort the info by the int values from ascending to descending. The file contains votes for a president from each state. I'm having trouble with the method, and right now it is returning the highest value first with it's state and printing it out 43 times and the last line is the smallest int value in the file. All in all, I just have to exchange the state along with the vote and display it accordingly.

Here is what I have so far:

public static void sort()
    {
        int startScan = 0; 
        int index = 0;
        int minIndex, minValue, stateIndex;
        String state = "";
        System.out.println("\n*Sorting");
        
        for(startScan = 0; startScan < data.length-1; startScan++)
        {
            minIndex = startScan;
            minValue = Integer.parseInt(data[0][2]);
            stateIndex = startScan;
            for(index = startScan + 1; index < data.length; index++)
            {
                if(Integer.parseInt(data[index][2]) > minValue)
                {
                    minValue = Integer.parseInt(data[index][2]);
                    minIndex = index;
                    state = data[index][0];

                }

            }
            data[minIndex][0] = data[startScan][0];
            data[minIndex][2] = data[startScan][2];
            data[startScan][2] = Integer.toString(minValue);
            data[startScan][0] = state;

        }

        for(int i=0; i<44; i++)
        {

            System.out.print(data[i][0] + "\t" + data[i][2]);

            System.out.println("");
        }
    }


Is This A Good Question/Topic? 0
  • +

Replies To: Sorting 2D Array with Selection Sort

#2 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8332
  • View blog
  • Posts: 31,857
  • Joined: 06-March 08

Re: Sorting 2D Array with Selection Sort

Posted 04 April 2011 - 08:45 PM

Never a good idea to try to sort parallel array and you complicate a lot your code whith all your Integer.parseInt()

You are better to write a class

class VoteByState implements Comparable<VoteByState> {

   private String state;
   private int vote;

   // constructor
   public VoteByState(int vote, String state) {
       this.vote = vote;
       this.state = state;
   }

   public int compareTo(VoteByState other) {
      return vote - other.vote;
   }
}



Then you can call a standard API sort method or white your own
Just two object to swap based on the value returned by compareTo()


macosxnerd101 wrote a good tutorial about that
http://www.dreaminco...arallel-arrays/
Was This Post Helpful? 1
  • +
  • -

Page 1 of 1