选择排序的代码实现
,下面的代码主要是通过两个函数,一个findSmallest()函数是用于查找最小的元素,selectionSort()函数是用于将列表进行排序。还有关于python的内置函数pop()的用法详解
def findSmallest(arr):#定义一个函数,用于查找最小元素
smallest=arr[0]
smallest_index=0
for i in range(1,len(arr)):
if arr[i] < smallest :
smallest = arr[i]
smallest_index = i
return smallest_index#函数返回值为最小元素的下标
def selectionSort(arr):#定义一个函数,用于对数组的重新排序
newArr=[]#新的空数组。为后面的数组排序提供位置
for i in range(0,len(arr)):
smallest=findSmallest(arr)
newArr.append(arr.pop(smallest))#pop()函数添加元素,根据下标进行,
return newArr
print(selectionSort([5,6,3,2,7]))
pop()
pop()内置函数的详解
```python
#pop()内置函数的用法详解
#pop()函数添加元素,根据下标进行,然后
#添加后,原数组的该元素将不会再留在原数组,例如
arr=[1,3,4,5,6]
newArr=[]
newArr.append(arr.pop(4))
print(newArr)
print(arr)
#输出结果为一下内容
[6]
[1, 3, 4, 5]