1

This Python code gives sorted elements according to string elements.
How we convert list elements, which are in string format in integer type?

This is my code:

def insertionSort(arr, n):
for i in range(1, n):
    key = arr[i]
    j = i - 1
    while j >= 0 and arr[j] > key:
        arr[j+1] = arr[j]
        j = j - 1
    arr[j+1] = key
print '\nSorted elements: ',    
return (' ').join(arr)

arr = (raw_input("enter elements: ")).split(',')  
print insertionSort(arr, len(arr))
1
  • you mean testing like this: int(arr[j]) > int(key) Commented Nov 9, 2017 at 12:35

1 Answer 1

2

you have to convert your elements using a element to key function so you can use comparison not of the element itself but of a transformed data suiting your needs.

I would do this as a generic solution:

def insertionSort(arr, n, keyfunc=lambda x:x):
    for i in range(1, n):
        key = arr[i]
        j = i - 1
        while j >= 0 and keyfunc(arr[j]) > keyfunc(key):
            arr[j+1] = arr[j]
            j = j - 1
        arr[j+1] = key
    return ' '.join(arr)

so by default, the key is just the element itself, but if you call your function like this:

insertionSort(arr, len(arr), keyfunc=int)

the key function is now "conversion to integer", and sorting works as expected on a list of integers as strings.

(note that the built-in sort method works that way, by allowing to provide a key function).

of course you can drop the whole keyfunc idea and just hardcode int here:

while j >= 0 and int(arr[j]) > int(key):
Sign up to request clarification or add additional context in comments.

Comments

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.