How to sort an array in a single loop?

后端 未结 22 2746
面向向阳花
面向向阳花 2020-12-19 09:14

So I was going through different sorting algorithms. But almost all the sorting algorithms require 2 loops to sort the array. The time complexity of Bubble sort & Insert

22条回答
  •  隐瞒了意图╮
    2020-12-19 09:29

    def my_sort(num_list):
        x = 0
        while x < len(num_list) - 1:
            if num_list[x] > num_list[x+1]:
                num_list[x], num_list[x+1] = num_list[x+1], num_list[x]
                x = -1
            x += 1
        return num_list
    
    print(my_sort(num_list=[14, 46, 43, 27, 57, 42, 45, 21, 70]))
    #output [14, 21, 27, 42, 43, 45, 46, 57, 70]
    

提交回复
热议问题