Skip to content
Advertisement

How to convert a char array to a number for sorting?

Let’s say I have three words I want to sort:

  • hello
  • goodbye
  • alex

And alphabetically it’d be sorted ascendingly as ["alex", "goodbye", "hello"]. Is there a way to convert the string (limited to 100 characters)? For example, if I have:

JavaScript

And I use ord to get the code for each list element:

JavaScript

How would I create a number from that, that would also be smaller than, say, goodbye?

Advertisement

Answer

Use:

JavaScript

Since you’ve bounded the length of the strings, you can think of each word as a base-27 number. 0 represents that the letter doesn’t exist, 1 represents a, 2 represents b, etc.

Then, the numerical value of each word can be computed using the following polynomial:

JavaScript

where char_vals = [i_1, i_2, ... i_{len(original_string)}] (i.e. each i is the integer value of the corresponding letter, and is that are past the end of the array correspond to zeroes).

Advertisement