选择排序的Python实现

选择排序是一种基础的排序算法,其基于数组的数据结构,这样的数据结构具有很强的灵活性,之所以说具有很强的灵活性呢,我们知道数组和顺序线性表结构是一种简单的存储结构,因为他们在逻辑上相邻的元素在物理内存之上也是彼此相邻的。而且同一个数组的数据类型必须是一致的,这样我们就可以通过数组的下标[index]进行随机顺序访问数组中的元素。这相比链表结构是做不到的,在链表的数据结构中,我们知道元素之间的逻辑相邻在物理内存中的实现是依靠指针的。这样一来,要得到链表种最后一个元素值的话,我们就需要从首节点依次访问到最后一个节点的数据域。

好了,上面废话了一下数组和链表的数据结构,下面我们来分析一下选择算法:
要实现把数组元素(数值)进行排列,我们有很多种算法。他们之间的算法效率也各不相同。
选择算法之所以叫做选择算法,其实呢可能是与其实现思路有关:

1.找到最小元素的索引

首先假定最小值是第一个数组元素:arr[0],对应的其索引为0;
对数组元素一一遍历,比较与假定的元素的大小,如果小于假定值,那么就交换彼此。
然后返回其索引作为函数的返回值 供选择排序算法使用
算法如下:

def getmin(arr):
    min = arr[0];
    min_index = 0;
    for i in range(0,len(arr)):
        if arr[i]<min:
            min = arr[i]
            min_index = i
    return min_index

2.对数组元素重组为有序数组

我们新建一个数组空newArr[;
t通过上面的比较最小值,得到每一个循环中的最小值的索引,得到对应值,并将其添加到newArr
代码实现:

def selectSort(arr):
    newArr = [];
    for i in range(0,len(arr)):
        min = getmin(arr);
        newArr.append(arr.pop(min))
    return newArr;

以下是完整代码块:

#selectSort which is a time-consuming sort algorithm.Its Time-complexity is O(N**2)
#1、we just use the simple sort algorithm to get the smallest number per loop,which the time-consuming is O(n)
#2、next we can define a function that a loop to get the small value every loop,and the append the value into a new Array
#to get the minmum value
def getmin(arr):
    min = arr[0];
    min_index = 0;
    for i in range(0,len(arr)):
        if arr[i]<min:
            min = arr[i]
            min_index = i
    return min_index

#SelectSort
def selectSort(arr):
    newArr = [];
    for i in range(0,len(arr)):
        min = getmin(arr);
        newArr.append(arr.pop(min))
    return newArr;

#test the output
a = [4,6,9,1,3,87,41,5]
print(selectSort(a))

运行结果:

这里写图片描述

猜你喜欢

转载自blog.csdn.net/sinat_38321889/article/details/80390238