数据结构 - 简单选择排序(simple selection sort) 详解 及 代码(C++)
2014-06-05 11:56
639 查看
数据结构 - 简单选择排序(simple selection sort)
本文地址: http://blog.csdn.net/caroline_wendy/article/details/28601965选择排序(selection sort) : 每一趟在n-i+1个记录中选取关键字最小的记录作为有序序列中第i个记录.
简单选择排序(simple selection sort) : 通过n-i次关键字之间的比较, 从n-i+1个记录中选出关键字最小的记录, 并和第i个记录交换.
选择排序需要比较n(n-1)/2次, 即(n-1)+(n-2)+...+1 = [(n-1)+1](n-1)/2次, 时间复杂度是O(n^2).
简单选择排序的主要步骤是: 1. 选出较小元素的位置. 2. 交换.
代码:
/*
* SimpleSelectionSort.cpp
*
* Created on: 2014.6.5
* Author: Spike
*/
#include <iostream>
#include <vector>
void print(const std::vector<int>& L) {
for (auto i : L) {
std::cout << i << " ";
}
std::cout << std::endl;
}
int SelectMinKey(std::vector<int>& L, const size_t p) {
int min = p;
for (size_t i=p+1; i<L.size(); ++i) {
if (L[i] < L[min]) {
min = i;
}
}
return min;
}
void SelectSort (std::vector<int>& L) {
for (size_t i=0; i<L.size(); ++i) {
size_t j = SelectMinKey(L, i);
if (i != j) std::swap(L[i], L[j]);
print(L);
}
}
int main(void) {
std::vector<int> L = {49, 38, 65, 97, 76, 13, 27, 49, 55, 4};
SelectSort(L);
print(L);
}
输出:
4 38 65 97 76 13 27 49 55 49
4 13 65 97 76 38 27 49 55 49
4 13 27 97 76 38 65 49 55 49
4 13 27 38 76 97 65 49 55 49
4 13 27 38 49 97 65 76 55 49
4 13 27 38 49 49 65 76 55 97
4 13 27 38 49 49 55 76 65 97
4 13 27 38 49 49 55 65 76 97
4 13 27 38 49 49 55 65 76 97
4 13 27 38 49 49 55 65 76 97
4 13 27 38 49 49 55 65 76 97
相关文章推荐
- 数据结构 - 只需选择排序(simple selection sort) 详细说明 和 代码(C++)
- 数据结构 - 树形选择排序 (tree selection sort) 详解 及 代码(C++)
- 数据结构 - 希尔排序(Shell's Sort) 详解 及 代码(C++)
- 数据结构 - 直接插入排序(Straight Insertion Sort) 详解 及 代码(C++)
- 数据结构 - 树形选择排序 (tree selection sort) 具体解释 及 代码(C++)
- 数据结构 - 折半插入排序(Binary Insertion Sort) 详解 及 代码(C++)
- 数据结构 - 堆排序(heap sort) 详解 及 代码(C++)
- php数据结构 算法(PHP描述) 简单选择排序 simple selection sort
- 数据结构&算法(PHP描述) 简单选择排序 simple selection sort
- 数据结构 - 冒泡排序(Bubble Sort) 详解 及 代码(C++)
- PHP实现排序算法----简单选择排序(Simple Selection Sort)
- 数据结构 - 堆排序(heap sort) 具体解释 及 代码(C++)
- 简单选择排序(Simple Selection Sort)的C语言实现
- 冒泡排序(bubble sort)、直接插入排序(straight insertion sort)、简单选择排序(simple selection sort)
- 选择排序—简单选择排序(Simple Selection Sort)
- 选择排序—简单选择排序(Simple Selection Sort)
- 数据结构 - 快速排序(Quick Sort) 详解 及 代码(C++)
- 简单选择排序(Simple Selection Sort)
- 八大排序算法之三选择排序—简单选择排序(Simple Selection Sort)