python selection sort time complexity

Selection Sort, Quick Sort, Hill Sort, Heap Sort are not stable sorting algorithms, while
Bubble Sort, Insertion Sort, Merge Sort and Radix Sort are stable sorting algorithms.
The meaning of the unstable sorting algorithm is that before sorting, there are two numbers that are equal. But after sorting, the two of them may change their order.

1 Introduction

Given a sequence of integers, arrange the integers in the sequence in ascending order (specifically, non-decreasing order)

The idea of ​​selection sort: select the smallest one and swap the first position, select the second smallest and swap the second position...
until the smallest one is selected from the Nth and N-1th elements and placed in the first N-1 positions.

2 Selection sort notation one

def select_sort(li):
    li_new = []
    for i in range(len(li)):
        # 选出数组li中的最小值
        min_val = min(li)
        print("i %d %d" % (i, min_val))
        # 向临时数组中添加最小元素
        li_new.append(min_val)
        # 移除原数组中的最小元素
        li.remove(min_val)
        
        print(li)

    return li_new

implement


li = [3, 2, 4, 7, 1, 2]
# 排序前
print(li)
print("-----------")
# 执行排序
netList = select_sort(li)
print("-----------")
# 排序后
print(netList)

insert image description here

3 Selection sort writing method 2

def select_sort2(li):
    for i in range(len(li) - 1):
        # 记录最小值的角标
        min_index = i
        for j in range(i + 1, len(li)):
            # 如果当前值小于 min_index 角标下的值 
            if li[j] < li[min_index]:
                # 就进行值替换 目的是将最小的值放在最左侧
                li[i], li[min_index] = li[min_index], li[i]
                print(li)

implement

li = [3, 2, 4, 7, 1, 2]
# 排序前
print(li)
print("-----------")
# 执行排序
select_sort2(li)
print("-----------")
# 排序后
print(li)

Results of the
insert image description here

4 Time complexity

The first inner loop compares N - 1 times, then N-2 times, N-3 times, ..., and the last inner loop compares 1 time.
The total number of comparisons is (N - 1) + (N - 2) + … + 1, and the arithmetic sequence sum is obtained to obtain (N - 1 + 1)* N / 2 = N^2 / 2.
The time complexity of discarding the highest term coefficient is O(N^2).

Although the time complexity of selection sort and bubble sort is the same, in practice, selection sort performs very few swap operations, and at most N - 1 swaps occur.
In the worst case of bubble sort, N^2 /2 swap operations occur. In this sense, the performance of swap sort is slightly better than bubble sort. Moreover, swap sort is more intuitive than the idea of ​​bubble sort.

Guess you like

Origin blog.csdn.net/zl18603543572/article/details/122330462