数据结构之排序(三)——简单选择排序
来源:互联网 发布:南宁直销软件多少钱 编辑:程序博客网 时间:2024/06/04 18:45
简单选择排序算法(Simple Selection Sort)就是通过n-i次关键字间的比较,从n-i+1个记录中选出关键字最小的记录,并和第i(1<=i<=n)个记录交换之。
原理
算法
#include "stdafx.h"using namespace std;#include<iostream>#include"stdafx.h"//用于要排序数组个数最大值,可根据需要修改 #define MAXSIZE 10 typedef struct{//用于存储要排序数组,r[0]用作哨兵或临时变量 int r[MAXSIZE + 1];//用于记录顺序表的长度 int length;}SqList;//交换L中数组r的下标为i和j的值 void swap(SqList *L, int i, int j) {int temp = L->r[i];L->r[i] = L->r[j];L->r[j] = temp;}//对顺序表L作简单选择排序void SelectSort(SqList *L) {int min;for (int i = 1; i < L->length; i++) {//将当前下标定义为最小值下标min = i;//循环之后的数据for (int j = i + 1; j <= L->length; j++) {//如果有小于当前最小值得关键字if (L->r[min] > L->r[j]) {//将此关键字的下标赋值给minmin = j;}}//若min不等于i,说明找到最小值,交换if (i != min)//交换L->r[i]与L->r[min]的值swap(L, i, min);}}#define N 9int main(){int d[N] = { 9,1,5,8,3,7,4,6,2 };SqList L0;for (int i = 0; i < N; i++) {L0.r[i + 1] = d[i];}L0.length = N;cout<< "排序前:";for (int j = 1; j < L0.length; j++) {cout<< L0.r[j];}SelectSort(&L0);cout << "\n简单选择排序后:";for (int j = 1; j < L0.length; j++) {cout << L0.r[j];}cout << endl;return 0;}
运行结果
简单选择排序复杂度分析
简单选择排序时间复杂度为:O(n^2)
但简单选择排序的性能上还是要略优于冒泡排序。
算法稳定性
不稳定
阅读全文