注意,交换后,x和y的值已被互换!
选择排序
有许多方法可以对数组进行排序。选择排序可能是理解最简单的排序,使这一教学很好的候选人,即使它是一个缓慢的种类。
选择排序执行以下步骤:
1)开始在指数0,搜索找到的最小值,整个数组
2)交换发现索引0处的值的最小值
3)重复步骤1和2从下一个指数
换句话说,我们要在阵列中找到最小的元素,并把它放在第一位。然后我们要找到下一个最小的元素,并把它放在第二位。这个过程将重复进行,直到我们跑出去的元素。
下面是一个例子,该算法工作的5要素。让我们开始与样品阵列:
30,50,20,10,40 }
首先,我们发现最小的元素,从索引0:
{ 30,50,20,10,40 }
然后我们交换这在索引0元:
{ 10,50,20,30,40 }
现在,第一个元素的排序,我们可以忽略它。因此,我们发现最小的元素,从索引1:
{ 10,50,20,30,40 }
并用指数1元:
{ 10,20,50,30,40 }
发现最小的元素开始的索引2:
{ 10,20,50,30,40 }
并用指数2元:
{ 10,20,30,50,40 }
发现最小的元素开始的索引3:
{ 10,20,30,50,40 }
并用指数3元:
{ 10,20,30,40,50 }
最后,发现最小的元素开始的索引4:
{ 10,20,30,40,50 }
并用指数4元(不做任何事):
{ 10,20,30,40,50 }
做!
{ 10,20,30,40,50 }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
const int nSize = 5;
int anArray[nSize] = { 30, 50, 20, 10, 40 };
// Step through each element of the array
for (int nStartIndex = 0; nStartIndex < nSize; nStartIndex++)
{
// nSmallestIndex is the index of the smallest element
// we've encountered so far.
int nSmallestIndex = nStartIndex;
// Search through every element starting at nStartIndex+1
for (int nCurrentIndex = nStartIndex + 1; nCurrentIndex < nSize; nCurrentIndex++)
{
// If the current element is smaller than our previously found smallest
if (anArray[nCurrentIndex] < anArray[nSmallestIndex])
// Store the index in nSmallestIndex
nSmallestIndex = nCurrentIndex;
}
// Swap our start element with our smallest element
swap(anArray[nStartIndex], anArray[nSmallestIndex]);
}