1

I'm trying to sort a list containing only lower case letters by using the string :

alphabet = "abcdefghijklmnopqrstuvwxyz". 

that is without using sort, and with O(n) complexity only. I got here:

def sort_char_list(lst):
alphabet = "abcdefghijklmnopqrstuvwxyz"
new_list = []
length = len(lst)

for i in range(length):
    new_list.insert(alphabet.index(lst[i]),lst[i])
    print (new_list)

return new_list

for this input :

m = list("emabrgtjh")

I get this:

['e']
['e', 'm']
['a', 'e', 'm']
['a', 'b', 'e', 'm']
['a', 'b', 'e', 'm', 'r']
['a', 'b', 'e', 'm', 'r', 'g']
['a', 'b', 'e', 'm', 'r', 'g', 't']
['a', 'b', 'e', 'm', 'r', 'g', 't', 'j']
['a', 'b', 'e', 'm', 'r', 'g', 't', 'h', 'j']
['a', 'b', 'e', 'm', 'r', 'g', 't', 'h', 'j']

looks like something goes wrong along the way, and I can't seem to understand why.. if anyone can please enlighten me that would be great.

8
  • 4
    You're inserting into your new_list at the index of your alphabet string... this won't sort your list. Commented Dec 9, 2014 at 20:32
  • 3
    Its not O(n) if you have to search the list each iteration (which is what index has to do). Commented Dec 9, 2014 at 20:32
  • why not? it looks like it's working until i=6. I would be glad if you can explain more (: Commented Dec 9, 2014 at 20:34
  • Try opening a python shell and writing: x = [], then x.insert(42, "foo"). You won't see "foo" in the 42nd entry of x, you'll see something else... Commented Dec 9, 2014 at 20:35
  • Does this need to handle duplicates? Commented Dec 9, 2014 at 20:37

1 Answer 1

3

You are looking for a bucket sort. Here:

def sort_char_list(lst):
    alphabet = "abcdefghijklmnopqrstuvwxyz"
    # Here, create the 26 buckets
    new_list = [''] * len(alphabet)

    for letter in lst:
        # This is the bucket index
        # You could use `ord(letter) - ord('a')` in this specific case, but it is not mandatory
        index = alphabet.index(letter)
        new_list[index] += letter

    # Assemble the buckets
    return ''.join(new_list)

As for complexity, since alphabet is a pre-defined fixed-size string, searching a letter in it is requires at most 26 operations, which qualifies as O(1). The overall complexity is therefore O(n)

Sign up to request clarification or add additional context in comments.

1 Comment

thank you so much, I'm so glad to learn new things and methods to deal with problems. I'm still very new to this, it is great this community exists to share great peoples' ideas. thanks again !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.