java - How to implement insertion sort to my ArrayList? -
i have homework problem i've been able easily, i'm stuck on how implement insertion sort arraylist i've constructed.
here's code far:
public class emaildirectory { public static void main(string[] args) { new emaildirectory(); //relay main menu until 3 entered } public arraylist<string> emailrecords=new arraylist<string>(); //construct array directory, array or arraylist? public emaildirectory() { scanner scnr=new scanner(system.in); //scanner , empty string option choice string menuchoice; do{ //do while keep repeating system.out.println("please enter number of option choice:"); system.out.println("1. add new contact"); system.out.println("2. search exsisting contact"); system.out.println("3. exit"); menuchoice=scnr.nextline(); if (menuchoice.equals("1")) //add new contact { addcontact(); } else if (menuchoice.equals("2")) //search contacts { searchcontact(); } } while(menuchoice.equals("3")==false); } private void addcontact() { scanner addcont=new scanner(system.in); //scanner new contact string newcont; system.out.println("please enter email adress."); //prompt user newcont=addcont.nextline(); emailrecords.add(newcont); //add array access later insertionsort(emailrecords); } private void searchcontact() { //todo system.out.println(emailrecords); //test output, change laster } public void insertionsort(arraylist<string> emailrecords) //insertion sort, pass parameter? { int i,j; string key; arraylist<string> inputarray=emailrecords; (j=1; j<inputarray.size(); j++) { key = inputarray.get(j); = j - 1; while (i >= 0) { if (key.compareto(inputarray.get(i)) > 0) { break; } string element=inputarray.get(i+1); element = inputarray.get(i); i--; } string element=inputarray.get(i+1); element = key; } } }
the homework problem create email directory , keep sorted using insertion, cant seem figure out why array wont sort. im able add emails, when print out appends end.
suggestions , advise appreciated, much!
fix sort function this:
public void insertionsort(arraylist<string> emailrecords) //insertion sort, pass parameter? { int i,j; string key; arraylist<string> inputarray=emailrecords; (j=1; j<inputarray.size(); j++) { key = inputarray.get(j); = j - 1; while (i >= 0) { if (key.compareto(inputarray.get(i)) > 0) { break; } string element=inputarray.get(i+1); //here inputarray.set(i+1,inputarray.get(i)); //here inputarray.set(i,element); //here i--; } key=inputarray.get(i+1); } } }
Comments
Post a Comment