Selection Sorting

We use some simple pictures to introduce

在这里插入图片描述在这里插入图片描述在这里插入图片描述

You can watch the animation on this website Visualization

Here is the code written in python with some useful annotate and optimization

# -*- coding: utf-8 -*-
"""
Created on Sun Jul 12 21:22:33 2020

@author: Gary
"""

#简单的选择排序
def selection_sort1(our_list):
    n=len(our_list)
    for i in range(n-1):
        mark=i
        for j in range(i+1,n):
            if our_list[j]<our_list[mark]:
                mark=j
        #最后再进行交换,减少内存的占用
        if mark!=i:
            our_list[i],our_list[mark]=our_list[mark],our_list[i]
    return our_list



#optimization
 #同时找出最小值与最大值放在数列两侧,两边逐渐逼近,循环次数会减少一些
def select_sort2(arr):
    n=len(arr)
    #整数除法
    for i in range(n//2):
        min_mark=i
        max_mark=n-i-1
        for j in range(i+1,n-i):
            if arr[j]<arr[min_mark]:
                min_mark=j
                
        if min_mark!=i:
            arr[i],arr[min_mark]=arr[min_mark],arr[i]
            
        for j in range(n-i-2,i,-1):
            if arr[j]>arr[max_mark]:
                max_mark=j
        if max_mark!=(n-i-1):
            arr[n-1-i],arr[max_mark]=arr[max_mark],arr[n-i-1]
    return arr
                

listtest=[33,15,66,88,1596,41156,4]

selection_sort1(listtest)
select_sort2(listtest)


#选择排序是种不稳定的排序,虽然代码有优化,但平均时间复杂度始终为 O(n^2)

Selection sort is an unstable algorithm.Alhough the code is optimized, the average time complexity is always O(n^2). Some sorting algorithm time complexity can be O(nlog2n)

猜你喜欢

转载自blog.csdn.net/Garyboyboy/article/details/107306591