dsjoka
dsjoka

Reputation: 61

Insertion sort with strings

I'm curious how an insertion sort would be for strings. I know how to do with numbers.

Could someone show me an implementation?

No, it's not for homework.

Thanks.

Upvotes: 0

Views: 2902

Answers (2)

Zach L
Zach L

Reputation: 16262

You should be able to adapt an insertion sort for numbers to Strings by using String.compareTo to determine whether Strings are 'less than' or 'greater than' each other.

Additionally, a quick google search turns up several implementations, like this one which uses the general Comparable interface (which String implements).

Upvotes: 1

Cameron Skinner
Cameron Skinner

Reputation: 54316

The sorting algorithm is pretty much the same no matter what you're sorting. The only difference is that with Strings (or any type of Object) you need to use the compareTo method rather than simply if (a < b).

Upvotes: 3

Related Questions