Java: Selection sort of String array -
i working on sort algorithms school project , have problem . following code not sorting array,i have tried same code array of numbers(the change in if) , working string array , use of compareto not working puts items in "random" order.
public static void selectionsortisbn(book pin[], int bookscounter) { (int x = 0; x < bookscounter; x++) { int minindex = x; (int y = x + 1; y < bookscounter; y++) { if (pin[y].getisbn().compareto(pin[minindex].getisbn()) < 0) { minindex = y; } } book temp = pin[x]; pin[x] = pin[minindex]; pin[minindex] = temp; } } edit:
i changed inner :
(int y = x + 1; y < bookscounter; y++) { int com=pin[y].getisbn().compareto(pin[minindex].getisbn()); system.out.println(pin[y].getisbn()+" "+pin[minindex].getisbn()+" = "+com); } and output getting
1537 1485 = 1 596 1485 = 4 1164 1485 = -3 909 1485 = 8 596 1537 = 4 1164 1537 = -4 909 1537 = 8 1164 596 = -4 909 596 = 4 909 1164 = 8
this working correctly, mistake making expect "596" under "1485", when not, sorting them strings, 596 > 1485 ba > aaaaba. add leading zeroes if want compare numbers alphanumerically.
Comments
Post a Comment