Hello, I have started to learn java for about 3 months, thus I don't know much about it. I want to write a short code that can sort an array of name by alphabetical order. I did it in two different ways, the 1st one worked, but the second ways did not. Would you please help me to correct the problem. Thanks a lot.
This is the one that worked
import java.util.*; public class testsortname{ public static void main (String args[]){ String s1= "Jerry";String s2= "AAA";String s3= "BTom";String s4= "AATom";String s5= "TDom"; String s6= "BlueBerry";String s7= "Samson";String s8= "Rinor";String s9= "Aladin";String s10= "FarFar"; String[] test=new String[10]; test[0]=s1;test[1]=s2;test[2]=s3;test[3]=s4;test[4]=s5; test[5]=s6;test[6]=s7;test[7]=s8;test[8]=s9;test[9]=s10; for(int j=0;j<test.length;j++){ System.out.println(test[j]);} System.out.println(s1.compareTo(s2)); System.out.println(s2.compareTo(s3)); int i=1; String[] b=new String[test.length];b[0]=test[0]; while (i<test.length){ int k = i-1;boolean condition = false; while(k>=0&&condition==false){ if(b[k].compareTo(test[i])<=0){ b[k+1]=test[i];condition=true; } else{b[k+1]=b[k];b[k]=test[i];k--;} } i++;} System.out.println("--------------------------------"); for(int j=0;j<b.length;j++){ System.out.println(b[j]); } } }
This is the one that didn't
import java.util.*; public class testsortname2{ public static void main (String args[]){ String s1= "Jerry";String s2= "AAA";String s3= "BTom";String s4= "AATom";String s5= "TDom"; String s6= "BlueBerry";String s7= "Samson";String s8= "Rinor";String s9= "Aladin";String s10= "FarFar"; String[] test=new String[10]; test[0]=s1;test[1]=s2;test[2]=s3;test[3]=s4;test[4]=s5; test[5]=s6;test[6]=s7;test[7]=s8;test[8]=s9;test[9]=s10; for(int j=0;j<test.length;j++){ System.out.println(test[j]);} String[] temp=new String[test.length]; temp[0]=test[0]; for(int i=1;i<10;i++){ int k=0; while(k<=i&&(test[i].compareTo(temp[k])>0)){k++;} for(int j=10;j<=k+1;j--){temp[j]=temp[j-1];} temp[k]=test[i]; } System.out.println("--------------------------------"); for(int j=0;j<temp.length;j++){ System.out.println(temp[j]); }}}