Python: How to sort the alphabet in a list without sorted functions?

44,479

Solution 1

Here's a very short implementation of the Quicksort algorithm in Python:

def quicksort(lst):
    if not lst:
        return []
    return (quicksort([x for x in lst[1:] if x <  lst[0]])
            + [lst[0]] +
            quicksort([x for x in lst[1:] if x >= lst[0]]))

It's a toy implementation, easy to understand but too inefficient to be useful in practice. It's intended more as an academic exercise to show how a solution to the problem of sorting can be written concisely in a functional programming style. It will work for lists of comparable objects, in particular for the example in the question:

unsort_list = ['B', 'D', 'A', 'E', 'C']
sort_list   = quicksort(unsort_list)

sort_list
> ['A', 'B', 'C', 'D', 'E']

Solution 2

just for fun:

from random import shuffle
unsorted_list = ["B", "D", "A", "E", "C"]

def is_sorted(iterable):
  for a1,a2 in zip(iterable, iterable[1:]):
     if a1 > a2: return False
  return True

sorted_list = unsorted_list
while True:
   shuffle(sorted_list)
   if is_sorted(sorted_list): break

the average complexity should be factorial and the worst case infinite

Solution 3

Python already know which string is first and which is next depending on their ASCII values

for example:

"A"<"B"
 True

so we can write a simple bubble sort algorithm to sort the list of strings

unsort_list = ["B", "D", "A", "E", "C"]
def sortalfa(unsort_list):
    for i in range(len(unsort_list)-1):
        for j in range(i+1,len(unsort_list)):
            if unsort_list[i]>unsort_list[j]:
                temp = unsort_list[i]
                unsort_list[i] = unsort_list[j]
                unsort_list[j] = temp
    print("sorted list:{}".format(unsort_list))

sortalfa(["B", "D", "A", "E", "C"])

Result:

sorted list:['A', 'B', 'C', 'D', 'E']

There are many standard libraries available by which can be done using single line of code.

Share:
44,479
Test_Subject
Author by

Test_Subject

Updated on July 07, 2020

Comments

  • Test_Subject
    Test_Subject almost 4 years

    This is not based on efficiency, and has to be done with only a very very basic knowledge of python (Strings, Tuples, Lists basics) so no importing functions or using sort/sorted. (This is using Python 2.7.3).

    For example I have a list:

    unsort_list = ["B", "D", "A", "E", "C"]
    sort_list = []
    

    sort_list needs to be able to print out:

    "A, B, C, D, E"
    

    I can do it with numbers/integers, is there a similar method for alphabetical order strings? if not what would you recommend (even if it isn't efficient.) without importing or sort functions.