In my exercice I made a sort algorithm. I have a text file and put it in a list.
text = file.read().split()
like this. So means my list contains numbers and letters in form of a string.
def insertion_sort(self, arr):
for i in range(1, len(arr)):
val = arr[i] #value
pos = i #position
while pos > 0 and val < arr[pos-1] :
arr[pos] = arr[pos-1] #Move elements ahead
pos -= 1
arr[pos] = val #sort the value to the correct position
The algorithm now sorts the numbers incorrectly of course. What would be the best solution to sort it correctly?
Edit: My string for example: ["1", "e", "2", "d", "10"] - Output that I get: 1,10,2,d,e - Output that I want: 1,2,10,d,e
With minimum changes from your code, you can extract "numbers" from your list and use exactly the same algorithm. For example:
def insertion_sort(arr):
arr_num = []
arr_str = []
# if the value is a number, then add it to arr_num, else to arr_str
for val in arr:
try:
arr_num.append(float(val))
except:
arr_str.append(val)
#your algorithm applied to arr_num
for i in range(1, len(arr_num)):
val = arr_num[i] #value
pos = i #position
while pos > 0 and val < arr_num[pos-1] :
arr_num[pos] = arr_num[pos-1] #Move elements ahead
pos -= 1
arr_num[pos] = val #sort the value to the correct position
#To convert back to string if needed
for i,val in enumerate(arr_num):
arr_num[i] = str(val)
#To concatenate list of numbers and string if needed
arr = arr_num+arr_str
return arr
And I get:
a = ["7", "c", "b", "10", "a"]
insertion_sort(a)
Out[57]: ['7.0', '10.0', 'c', 'b', 'a']
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.