1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <algorithm> // for std::swap, use <utility> instead if C++11
#include <iostream>
int main()
{
const int length = 5;
int array[length] = { 30, 50, 20, 10, 40 };
// Step through each element of the array
for (int startIndex = 0; startIndex < length; ++startIndex)
{
// smallestIndex is the index of the smallest element we've encountered so far.
int smallestIndex = startIndex;
// Look for smallest element remaining in the array (starting at startIndex+1)
for (int currentIndex = startIndex + 1; currentIndex < length; ++currentIndex)
{
// If the current element is smaller than our previously found smallest
if (array[currentIndex] < array[smallestIndex])
// This is the new smallest number for this iteration
smallestIndex = currentIndex;
}
// Swap our start element with our smallest element
std::swap(array[startIndex], array[smallestIndex]);
}
// Now print our sorted array as proof it works
for (int index = 0; index < length; ++index)
std::cout << array[index] << ' ';
return 0;
该算法最令人迷惑的部分是另一个循环内的循环(称为嵌套循环).。外环(指数)遍历每个元素一个接一个。每一次迭代中的外环、内环(currentindex)是用来在剩下的阵列中找到最小的元素(从startIndex + 1)。smallestindex跟踪由内环发现最小的元素的索引。然后smallestindex是交换的字符。最后,外环(指数)提出的一个元素,和重复的过程。
提示:如果你很难理解上面的程序是如何工作的,那么通过在一张纸上取样的例子可以很有帮助.。写出发(无序)水平在试卷顶端的数组元素。画箭头指示元素startIndex currentindex,和smallestindex索引。手动跟踪程序和重绘箭头作为指标变化。对于外部循环的每次迭代,启动一个新的行,显示数组的当前状态.。
排序名称使用相同的算法。只需改变数组的类型从int到std::string,并用适当的值初始化。
测验
1)手动显示如何选择排序工作在下列数组:{ 30,60,20,50,40,10。显示每个交换发生后的数组。
2)重写上面的选择排序代码按降序排序(最大数量优先)。虽然这似乎很复杂,但实际上却是出奇的简单。
3)这将是困难的,所以把你的游戏脸。
另一种简单的排序叫做“冒泡排序”。冒泡排序是通过比较相邻的元素对,在满足条件时交换它们,使元素“冒泡”到数组的末端.。虽然有相当多的方法来优化的冒泡排序,这个测验我们就坚持用未优化的版本在这里因为它是简单的。
未经优化的冒泡排序执行以下步骤来从最小到最大数组排序:
比较数组元素0与数组元素1。如果元素0较大,用元素1交换它。
B)现在对元素1和2,以及随后的一对元素做同样的处理,直到你击中数组的末端.。此时,数组中的最后一个元素将被排序.。
重复前两个步骤,直到数组被排序。
根据上面的规则编写冒泡代码对下面的数组进行排序: