Java String Bubble Sorting -
i need sorting array in alphabetical order using bubble sort algorithm.
my code is:
public class strings { public static void main(string[] args) { scanner reader = new scanner(system.in); string tempstr; system.out.print("enter strings > "); string s1 = new string(reader.nextline()); string[] t1 = s1.split(", "); (int t=0; t<t1.length-1; t++) { (int = 0; i<t1.length -1; i++) { if(t1[i+1].compareto(t1[1+1])>0) { tempstr = t1[i]; t1[i] = t1[i+1]; t1[i+1] = tempstr; } } } for(int i=0;i<t1.length;i++) { system.out.println(t1[i]); } } }
the code compiles, not sort alphabetical. please me.
you have 3 errors in code.
the first error in inner loop, in place check statement, should i < t1.length - t -1
not i < t1.length -1
. subtract t because not want loop through whole array again, first part of it.
the second , third errors in if statement. need turn greater symbol lesser symbol, because way have compareto method set up, return negative number.
the other error in line in compareto parameter put 1 + 1
should i
, because want 1 less object comparing to.
the fixed working code below (comments had):
public static void main(string[] args) { scanner reader = new scanner(system.in); string tempstr; system.out.print("enter strings > "); string s1 = new string(reader.nextline()); string[] t1 = s1.split(", "); (int t = 0; t < t1.length - 1; t++) { (int i= 0; < t1.length - t -1; i++) { if(t1[i+1].compareto(t1[i])<0) { tempstr = t1[i]; t1[i] = t1[i + 1]; t1[i + 1] = tempstr; } } } (int = 0; < t1.length; i++) { system.out.println(t1[i]); } }
Comments
Post a Comment