简体   繁体   中英

python program to sort a list in ascending order without using the sort function

//it only works for numbers //i want it to work for string as well

def method(list):
   for i in range(len(list)):
      for j in range(i+1,len(list)):
          if list[i]>list[j]:
                list[i],list[j]=list[j],list[i]
return list

Your code looks good and will be able to sort a list of strings as well.

You just need to make small fixes. Try the below code:

def my_sorting(input_list):
   for i in range(len(input_list)):
      for j in range(i+1,len(input_list)):
          if input_list[i] > input_list[j]:
              input_list[i],input_list[j] = input_list[j],input_list[i]
   return input_list

Sample input/output:

Input ---> input_list = ["zas", "app", "zaa", "abc", "aaz"]

Output ---> ['aaz', 'abc', 'app', 'zaa', 'zas']

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM