一、选择排序
首先在未排序中找出最小的元素,存放到排序序列的起始位置,然后再从剩余的未排序序列中选出最小的元素
放在已排序的末尾(未排序的首位)
二、选择排序的特点
1、选择排序对文件本身的顺序依赖很低,运行时间与输入无关
2、长度为N的序列,最多需要比较N次,数据移动是所有排序算法中最少的
3、比较次数是N(N-1)/2
4、赋值操作介于0~3(N-1)
5、时间复杂度 O(N²)
6、选择排序是不稳定的排序
三、代码实现
#include <iostream>
#define Less(a,b) if(a<b)
using namespace std;
template <typename type>
void Exch(type& a, type& b)
{
type temp = a;
a = b;
b = temp;
}
template <typename type>
void SelectionSort(type data[], int length)
{
//两次遍历,找出最小的数,交换位置
for (int i = 0; i < length; i++)
{
int MinIndex = i;
//内循环找出剩余序列中的最小数据的下标
for (int j = i + 1; j < length; j++)
{
if (data[j]<data[MinIndex])
MinIndex = j;
}
//将找到的最小值放在未排序的起始位置
Exch(data[i], data[MinIndex]);
}
}
template <typename type>
void PrintList(type data[], int length)
{
for (int i = 0; i < length; i++)
cout << data[i] << "\t";
}
int main()
{
int a[] = { 2, 1, 4, 3, 6, 5, 8, 7, 9, 0 };
char t[] = { 'a', 'c', 'b', 'g', 'd', 'f', 'e' };
SelectionSort(a, 10);
PrintList(a, 10);
SelectionSort(t, 7);
PrintList(t, 7);
return 0;
}
python
#coding=gbk
'''
@author: Nicholas
'''
class Sort():
def SelectionSort(self,data):
for i in range(len(data)):
minIndex = i
for j in range(i+1,len(data)):
if data[j] < data[minIndex]:
minIndex = j
data[i],data[minIndex] = data[minIndex],data[i]
def PrintData(self,data):
for e in data:
print(e)
if __name__ == '__main__':
data=[1,0,9,2,3,8,6,7,4,5]
s = Sort()
s.SelectionSort(data)
s.PrintData(data)