3

I'm trying to sort the contents of an array and while it seems to be working (no runtime errors; is performing sort tasks), the first 10 rows, while sorted, are not in order with the rest of the rows.

class coordSort.java

import java.io.*;
import java.util.Arrays;
import java.util.Scanner;

public class coordSort {
@SuppressWarnings({ "unchecked", "unused" })
public static void main (String args[]) throws IOException {

    String xCoord, yCoord;
    int coordSum;
    Scanner input = new Scanner(System.in);

    //Get x coordinate from user
    System.out.print("Enter x coordinate: ");
    xCoord = input.next();

    //Get x coordinate from user
    System.out.print("Enter y coordinate: ");
    yCoord = input.next();

    boolean sort = false;

    char[] a = xCoord.toCharArray();
    char[] b = yCoord.toCharArray();

    //validate user input is a digit 
    if ( (Character.isDigit(a[0]))  ) {     
        if(Character.isDigit(b[0]) ){
            //digits entered - begin processing all coordinate values
            sort = true;
        }
    }

    //If validation failed, inform user
    if(!sort){
        System.out.println("Please enter a positive numeric value.");
    }

    if(sort){       
        //determine SUM of user entered coordinates
        coordSum = Integer.parseInt(xCoord) + Integer.parseInt(yCoord);

        //define coordinate array
        String[][] coordUnsortedArray = new String[26][3];
        int counter;
        int commaCount;
        String xCoordIn, yCoordIn;
        int intXCoordIn, intYCoordIn, sumCoordIn, coordDiff;

        //define input file
        FileInputStream fileIn = new FileInputStream("coords.txt");
        BufferedReader reader = new BufferedReader(new InputStreamReader(fileIn)); 

        for (int j = 0; j < coordUnsortedArray.length; j++){
            counter = 0;
            commaCount = 0;
            //line from file to variable
            String coordSet = reader.readLine();     

            //look for the second "," to determine end of x coordinate
            for(int k = 0; k < coordSet.length(); k++){
                if (coordSet.charAt(k) == ',') {
                    commaCount++;
                    counter++;
                    if (commaCount == 2){
                        break;
                    }
                }else{
                    counter++;
                }
            }

            //define x coordinate
            xCoordIn = (coordSet.substring(2,(counter - 1)));
            intXCoordIn = Integer.parseInt(xCoordIn);

            //define y coordinate
            yCoordIn = (coordSet.substring((counter),coordSet.length()));
            intYCoordIn = Integer.parseInt(yCoordIn);

            //coordinate calculations
            sumCoordIn = Integer.parseInt(xCoordIn) + Integer.parseInt(yCoordIn);
            coordDiff = sumCoordIn - coordSum;

            //load results to array
            coordUnsortedArray[j][0] = xCoordIn;
            coordUnsortedArray[j][1] = yCoordIn;
            coordUnsortedArray[j][2] = Integer.toString(coordDiff);

            //Output Array (BEFORE SORTING)
            //System.out.println((j + 1) + ") " + coordUnsortedArray[j][0] + " : " + coordUnsortedArray[j][1] + " : " + coordUnsortedArray[j][2]);                  
        }             

        System.out.println("\n");

        fileIn.close();

        String[][] coordsSorted = new String[26][3];

        //Sort array coordDiff, column 3
        Arrays.sort(coordUnsortedArray, new ColumnComparator(2));

        //Print the sorted array
        for(int i = 0; i < coordUnsortedArray.length; i++){
            String[] row = coordUnsortedArray[i];
            System.out.print((i + 1) + ") ");
            for(int j = 0; j < row.length; j++) {
                //System.out.print(row[j] + " | ");
                coordsSorted[i][j] = row[j];
                System.out.print(coordsSorted[i][j] + " : ");
            }
            System.out.print("\n");
        }
    }
}
}

class sortCoords.java --

import java.util.Comparator;

@SuppressWarnings("rawtypes")
class ColumnComparator implements Comparator {
    int columnToSort;
    ColumnComparator(int columnToSort) {
        this.columnToSort = columnToSort;
    }
    //overriding compare method
    public int compare(Object o1, Object o2) {
        String[] row1 = (String[]) o1;
        String[] row2 = (String[]) o2;
        //compare the columns to sort
        return row1[columnToSort].compareTo(row2[columnToSort]);
    }

    //overriding compare method
    public int compare1(Object o1, Object o2) {
        String[] row1 = (String[]) o1;
        String[] row2 = (String[]) o2;
        //compare the columns to sort
        return row1[columnToSort].compareTo(row2[columnToSort]);
    }
} 

I am trying to sort the array in numerical order by the 3rd column. The unsorted array is populated by a text file containing something like:

a,44,67

b,31,49

c,93,6

I am performing calculations on the array compared to user input and populating the array as follows:

44,67,101

31,49,70

93,6,89

I would like the sortedArray to output the following:

31,49,70

93,6,89

44,67,101

2
  • 2
    Welcome - it would help if you could clarify how you want them sorted and perhaps the output right now and an example of the correct output.
    – dfb
    Apr 9, 2012 at 17:26
  • Hi, thanks for the fast response. I am trying to sort the array in numerical order by the 3rd column. The unsorted array is populated by a text file containing something like: a,44,67 b,31,49 c,93,6 I am performing calculations on the array compared to user input and populating the array as follows: 44,67,101 31,49,70 93,6,89 I would like the sortedArray to output the following: 31,49,70 93,6,89 44,67,101 Apr 9, 2012 at 17:45

3 Answers 3

2

One possible confusion here:

 return row1[columnToSort].compareTo(row2[columnToSort])

This is a string comparison, not a numerical one. If you sort based on strings, you will get different results than if you do by numbers - ie "1","10","100","9" vs 1,9,10,100

Check out Integer.parseInt and if you can't figure out the rest, feel free to ask more questions.

3
  • Please see my response above. Apr 9, 2012 at 17:49
  • I think what you've written is consistent with my answer, see my edits
    – dfb
    Apr 9, 2012 at 17:53
  • I was wondering if you could take a look at my error below? I can't seem to get it working... Any thoughts, advice, or examples would be most helpful. Thanks again for everything to this point! Apr 9, 2012 at 21:47
1

As spinning_plate stated. You need to compare their int values i.e. you need a cast there

    int num1 = Integer.parseInt(row1[columnToSort]);
    int num2 = Integer.parseInt(row2[columnToSort]);
    if(num1 > num2)
            return 1;
    else 
            return 0;

Place this code in the compareTo method and check. Swap the return statements to sort in reverse order.

Also, adding some error checking in the compareTo method will make the code more efficient.

5
  • Thanks again for the responses. When entering: return Integer.parseInt(row1[columnToSort]).Integer.parseInt(compareTo(row2[columnToSort])); I have errors under the second Integer and compareTo My apologies, but I'm new to Java... Apr 9, 2012 at 18:00
  • My mistake. Parenthesis and parseInt were at the wrong place. Fixed it. Please try and let me know any error.
    – mtk
    Apr 9, 2012 at 18:08
  • Now the whole line is erroring. Error says, "Cannot invoke compareTo(int) on the primitive type int". Apr 9, 2012 at 18:27
  • So I've tried several different things to eliminate the errors, but can't seem to get it right... I have found that if I change "String[] row1 = (String[]) o1;" to "int[] row1 = (int[]) o1;", only parseInt shows an error, but I'm sure that's because the variable type has changed. If I remove the parsing, then the whole line erros again with "Cannot invoke compareTo(int) on the primitive type int'. I'm at a loss. Any further tips and advice is certainly appreciated. Thanks again for the responses!! Apr 9, 2012 at 19:21
  • Hey thanks for the update. The cod is running, only now the output is not sorting at all. I think I understand what the idea is - convert to int variable type for correct sorting, then, if num1 < num2, return 0 tp leave the row in its current position. Unless I'm not entering the code correctly, despite returning 0 or 1, there is no sorting going on. Apr 11, 2012 at 3:18
0

Ok, so after the assistance provided here, below is the solution that we found. Thanks again for the help everyone! Hopefully the code below helps someone else out.

Code for class1 --

import java.io.*;
import java.util.Arrays;
import java.util.Scanner;

public class coordSort {
    @SuppressWarnings({ "unchecked" })
    public static void main (String args[]) throws IOException {

        String xCoordChar, yCoordChar;
        int xCoord, yCoord, coordSum;
        Scanner input = new Scanner(System.in);

        //Get x coordinate from user
        System.out.print("Enter x coordinate: ");
        xCoordChar = input.next();

        //Get x coordinate from user
        System.out.print("Enter y coordinate: ");
        yCoordChar = input.next();

        boolean sort = false;

        char[] a = xCoordChar.toCharArray();
        char[] b = yCoordChar.toCharArray();

        //validate user input is a digit 
        if ( (Character.isDigit(a[0]))  ) {     
            if(Character.isDigit(b[0]) ){
                //digits entered - begin processing all coordinate values
                sort = true;
            }
        }

        //If validation failed, inform user
        if(!sort){
            System.out.println("Please enter a positive numeric value.");
        }

        if(sort){       
            //Parse user input characters to Integers
            xCoord = Integer.parseInt(xCoordChar);
            yCoord = Integer.parseInt(yCoordChar);

            //determine SUM of user entered coordinates
            coordSum = xCoord + yCoord;

            //define coordinate array
            int[][] coordUnsortedArray = new int[26][3];
            int counter;
            int commaCount;
            String xCoordIn, yCoordIn;
            int intXCoordIn, intYCoordIn, sumCoordIn, coordDiff;

            //define input file
            FileInputStream fileIn = new FileInputStream("coords.txt");
            BufferedReader reader = new BufferedReader(new InputStreamReader    (fileIn)); 

            for (int j = 0; j < coordUnsortedArray.length; j++){
                counter = 0;
                commaCount = 0;
                //line from file to variable
                String coordSet = reader.readLine();     

                //look for the second "," to determine end of x coordinate
                for(int k = 0; k < coordSet.length(); k++){
                    if (coordSet.charAt(k) == ',') {
                        commaCount++;
                        counter++;
                        if (commaCount == 2){
                            break;
                        }
                    }else{
                        counter++;
                    }
                }

                //define x coordinate
                xCoordIn = (coordSet.substring(2,(counter - 1)));
                intXCoordIn = Integer.parseInt(xCoordIn);

                //define y coordinate
                yCoordIn = (coordSet.substring((counter),coordSet.length()));
                intYCoordIn = Integer.parseInt(yCoordIn);

                //coordinate calculations
                sumCoordIn = Integer.parseInt(xCoordIn) + Integer.parseInt    (yCoordIn);
                coordDiff = sumCoordIn - coordSum;

                if (coordDiff < 0){
                    coordDiff = coordDiff * (-1);
                }

                //load results to array
                coordUnsortedArray[j][0] = intXCoordIn;
                coordUnsortedArray[j][1] = intYCoordIn;
                coordUnsortedArray[j][2] = coordDiff;                           
            }             

            fileIn.close();
            System.out.print("\n");
            System.out.println("Array Before Sorting:");
            System.out.println("=====================");

            //Array Before Sorting
            for(int i = 0; i < coordUnsortedArray.length; i++){
                int[] row = coordUnsortedArray[i];
                System.out.print((i + 1) + ") ");
                for(int j = 0; j < (row.length - 1); j++) {
                    coordUnsortedArray[i][j] = row[j];
                    if(j < 1){
                        System.out.print(coordUnsortedArray    [i]    [j] + ",");   
                    }else{
                        System.out.println(coordUnsortedArray    [i]    [j]);
                    }
                }
            }

            System.out.print("\n");
            System.out.print("\n");

            //Sort array coordDiff, column 3
            Arrays.sort(coordUnsortedArray, new ColumnComparator(2));

            System.out.println("Array After Sorting:");
            System.out.println("====================");

            //Original Array After Sorting
            for(int i = 0; i < coordUnsortedArray.length; i++){
                int[] row = coordUnsortedArray[i];
                System.out.print((i + 1) + ") ");
                for(int j = 0; j < (row.length - 1); j++) {
                    coordUnsortedArray[i][j] = row[j];
                    if(j < 1){
                        System.out.print(coordUnsortedArray[i][j] + ",");   
                    }else{
                        System.out.println(coordUnsortedArray    [i]    [j]);
                    }
                }
            }
            }
        }
}

Code for class2 --

import java.util.Comparator;

@SuppressWarnings("rawtypes")
class ColumnComparator implements Comparator {
int columnToSort;
ColumnComparator(int columnToSort) {
this.columnToSort = columnToSort;
}

//Compare method
public int compare(Object o1, Object o2) {
    int[] row1 = (int[]) o1;
    int[] row2 = (int[]) o2;

    int intRow1 = (row1[columnToSort]);
    int intRow2 = (row2[columnToSort]);

    return new Integer(intRow1).compareTo(new Integer(intRow2));
}
}    
1
  • No. That code does not work in the way you intended. It does not sort and does not display the values correctly. Oct 7, 2013 at 21:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.