Reputation: 49
I want to sort the array according to column wise(ascending order).The method sortByrollNum works correctly.But in second method sortByPer the highest number print on the top.It should be print according ascending order as the first method do.I tried a lot.Can anybody help me how to fix it?
public static int compareStrings(String str1,String str2){
int check=str1.compareTo(str2);
return check;
}//RollNumCheck
public static void sortByRollNum(String [] [] arr,int currentSize){
String minName=arr[0][0];
String minRollNum=arr[0][1];
String minPer=arr[0][2];
for(int j=0;j<arr.length-1;j++){
for(int i=0;i<arr.length-j-1;i++){
int check=compareStrings(arr[i][1], arr[i+1][1]);
if(check>0){
minName=arr[i+1][0];
minRollNum=arr[i+1][1];
minPer=arr[i+1][2];
arr[i+1][0]=arr[i][0];
arr[i+1][1]=arr[i][1];
arr[i+1][2]=arr[i][2];
arr[i][0]=minName;
arr[i][1]=minRollNum;
arr[i][2]=minPer;
}//if
}//for
}//for
System.out.print("\nSorted Array according to Roll Number.\n");
printArray(arr);
}//sortByRollNum
public static void sortByPer(String [] [] arr,int currentSize){
String minName=arr[0][0];
String minRollNum=arr[0][1];
String minPer=arr[0][2];
for(int j=0;j<arr.length-1;j++){
for(int i=0;i<arr.length-j-1;i++){
int check=compareStrings(arr[i][2], arr[i+1][2]);
if(check>0){
minName=arr[i+1][0];
minRollNum=arr[i+1][1];
minPer=arr[i+1][2];
arr[i+1][0]=arr[i][0];
arr[i+1][1]=arr[i][1];
arr[i+1][2]=arr[i][2];
arr[i][0]=minName;
arr[i][1]=minRollNum;
arr[i][2]=minPer;
}//if
}//for
}//for
System.out.print("\nSorted Array according to Percentage.\n");
printArray(arr);
}//sortByPer
Upvotes: 0
Views: 463
Reputation: 76
It seems like the problem is in your implementation of the compareString(String str1,String str2)
method. When you use the String.compareTo(String)
function, it compares the two strings by converting them to Unicode values to compare. Even the sortByRollNum()
function would not work in all cases, it was just lucky that it did.
My suggestion would be since you're comparing the Roll Numbers and Percentages, parse out the integer values and compare those. You can use Integer.parseInt(String)
to do so but the string must contain only numeric values.
About compareTo: https://beginnersbook.com/2013/12/java-string-compareto-method-example/
Upvotes: 1