For Programmers: Free Programming Magazines  


Home > Archive > Java Help > June 2007 > Sort Method Conversion









You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

 

Author Sort Method Conversion
kaltizer

2007-06-27, 10:09 pm

I need to modify this method to sort an array of strings rather than
chars:

// selectionSort(): sorts the elements of a
public static void selectionSort(char[] v) {
for (int i = 0; i < v.length-1; ++i) {
// guess the location of the ith smallest element
int guess = i;
for (int j = i+1; j < v.length; ++j) {
if (v[j] < v[guess]) { // is guess ok?
// update guess to index of smaller element
guess = j;
}
}

// guess is now correct, so swap elements
char rmbr = v[i];
v[i] = v[guess];
v[guess] = rmbr;
}
}

}

Any ideas?

hiwa

2007-06-27, 10:09 pm

On Jun 28, 9:07 am, kaltizer <kevinalti...@gmail.com> wrote:
> I need to modify this method to sort an array of strings rather than
> chars:
>
> // selectionSort(): sorts the elements of a
> public static void selectionSort(char[] v) {
> for (int i = 0; i < v.length-1; ++i) {
> // guess the location of the ith smallest element
> int guess = i;
> for (int j = i+1; j < v.length; ++j) {
> if (v[j] < v[guess]) { // is guess ok?
> // update guess to index of smaller element
> guess = j;
> }
> }
>
> // guess is now correct, so swap elements
> char rmbr = v[i];
> v[i] = v[guess];
> v[guess] = rmbr;
> }
>
> }
> }
>
> Any ideas?


You could use String.compareTo() method for string comparison, instead
of < operatot.

Roedy Green

2007-06-28, 8:09 am

On Wed, 27 Jun 2007 17:07:36 -0700, kaltizer <kevinaltizer@gmail.com>
wrote, quoted or indirectly quoted someone who said :

>I need to modify this method to sort an array of strings rather than
>chars:



To write general purpose sorts you need the Comparable or Comparator
interface. You implement the interface to do the compare, and your
sort uses only the methods of those interfaces to do the comparing.

See http://mindprod.com/jgloss/sort.html

http://mindprod.com/jgloss/comparable.html (to define the natural
order)

http://mindprod.com/jgloss/comparator.html(to define alternate orders)
--
Roedy Green Canadian Mind Products
The Java Glossary
http://mindprod.com
Sponsored Links







Also available: Server administration forum archive | Web Design forum archive | Software forum archive | Hardware reviews archive

Copyright 2008 codecomments.com