Monday, 15 March 2010

java - How to alter a bubble sort from numeric to alphabetical? -



java - How to alter a bubble sort from numeric to alphabetical? -

i using arraylist book titles , book ratings. how can alter code create bubble sort alphabetical instead of numeric?

system.out.println("\r" + "in order rating"); (int out = 0; out < booklist.size(); out++) { (int in = 0; in < booklist.size() - 1; in++) if (booklist.get(in).getrating() < booklist.get(in + 1).getrating()) { book temp = booklist.get(in); booklist.set(in, booklist.get(in+1)); booklist.set(in+1, temp); } system.out.println(videolist.get(out).gettitle() + " " + videolist.get(out).getrating()); } }

my other classes below.

book

public class book { string title; int rating; public book(string ptitle, int prating) { title = ptitle; rating = prating; } public string gettitle() { homecoming title; } public int getrating() { homecoming rating; } public void settitle(string newtitle) { title = newtitle; } public void setrating(int newrating) { rating = newrating; } }

library

import java.util.arraylist; public class library { public static void main (string [] args) { arraylist<book> booklist = new arraylist<book>(); book b1 = new book ("huckleberry finn", 5); book b2 = new book ("the great gadsby", 2); book b3 = new book ("harry potter", 3); book b4 = new book ("animal farm", 4); book b5 = new book ("the mist", 1); booklist.add(b1); booklist.add(b2); booklist.add(b3); booklist.add(b4); booklist.add(b5); system.out.println("original sequence"); (int cnt = 0; cnt < videolist.size(); cnt++) { system.out.println(booklist.get(cnt).gettitle() + " " + booklist.get(cnt).getrating()); } } }

is there way alter code in algorithm class display booklist sorted title?

you can't utilize < straight on 2 strings, can utilize compareto.

if (booklist.get(in).gettitle().compareto(booklist.get(in + 1).gettitle()) < 0) { ...

if s1 , s2 strings, s1.compareto(s2) returns negative value if s1 lexicographically less s2, positive value if s1 greater, , 0 if 2 strings equal.

java bubble-sort

No comments:

Post a Comment