java - Sort strings in an array based on length -


i have below program sorting strings based on length. want print shortest element first. don't want use comparator or api this. if please give me inputs on going wrong, i'd appreciate it. ps: please go easy on comments/ downvotes chemical engineer, , trying learn java on own. been month :)

public class sortarrayelements {     public static void main(string[] args) {     string[] arr = new string[]{"fan","dexter","abc","fruit","apple","banana"};     string[] sortedarr = new string[arr.length];      for(int i=0;i<sortedarr.length;i++)     {                    sortedarr[i] = comparearrayelements(arr);                            }      system.out.println("the strings in sorted order of length are: ");     for(string sortedarray:sortedarr)     {         system.out.println(sortedarray);     }  }  public static string comparearrayelements(string[] arr) {     string temp = null;     for(int i=0;i<arr.length-1;i++)     {         temp = new string();         if(arr[i].length() > arr[i+1].length())             temp = arr[i+1];         else             temp = arr[i];     }     return temp; } 

}

if want learn java: use comparator. other way bad java code.

you can rewrite comparator system if want, teach proper code structuring.

for actual code, here hints:

  • using proper algorithm more important language use code. algorithms same, no matter language.

  • do never new in loops, unless need create new objects. gc says "thanks".

  • change comparearrayelements function accept minimum size , have return smallest string @ least minimum size.

  • you cut out strings have considered smallest (set them null), modify original array.

Comments

Popular posts from this blog

java.util.scanner - How to read and add only numbers to array from a text file -

rewrite - Trouble with Wordpress multiple custom querystrings -