参考下面的几幅图,红色表示当前找到的未排序序列中的最小值,绿色表示当前被比较的元素:
又找到一个更小的值2,重新标记它为红色:
一轮比较后,找到最小值2并标记为黄色,表示就位,继续在未排序序列中寻找最小值:
def selection_sort(our_list):
# 补全代码
#
#
return our_sorted_list
参考本文对选择排序的一些提示,在星球内记录代码及思考过程。
#include "stdafx.h"
#include<iostream>
#include<vector>
using namespace std;
//简单选择排序时间复杂度为o(n*n),空间复杂度为o(1)
void SelectSort(vector<int> &R)
{
int temp, k; //temp用来存储临时变量, k用来存储最小值的index
for (unsigned int i = 0; i < R.size(); i++)
{
k = i;
//此循环是算法的关键,它挑出无序数组中最小的一个元素
for (unsigned int j = i;j < R.size(); j++)
{
if (R[k] > R[j])
{
k = j;
}
}
//将最小元素与无序序列第一个元素交换
temp = R[i];
R[i] = R[k];
R[k] = temp;
}
}
int main()
{
vector<int> R = { 3, 5, 2, 9, 7, 8, 4, 1, 6, 10 };
SelectSort(R);
for (auto x : R)
cout << x << " ";
cout << endl;
return 0;
}
python 版本
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/3/13 15:38
# @Author : caius
# @Site :
# @File : select_sort.py
# @Software: PyCharm
'''
选择排序
选择排序是一种简单直观的排序算法,无论什么数据进去都是 O(n²) 的时间复杂度。所以用到它的时候,数据规模越小越好。唯一的好处可能就是不占用额外的内存空间了吧。
1. 算法步骤
首先在未排序序列中找到最小(大)元素,存放到排序序列的起始位置
再从剩余未排序元素中继续寻找最小(大)元素,然后放到已排序序列的末尾。
重复第二步,直到所有元素均排序完毕。
'''
def selectionsort(arr):
for i in range(len(arr)-1):
# 记录最小值的索引
minIndex = i
for j in range(i+1,len(arr)):
if arr[j] <arr[minIndex]:
minIndex = j
# i 不是最小数是,将i和最小数进行交换
if i!= minIndex:
arr[i],arr[minIndex] = arr[minIndex],arr[i]
return arr
if __name__ == '__main__':
arr = [3,44,38,5,47,15,36,26,27,3,46,4,19,50,48]
print(selectionsort(arr))