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 }
这里的如何,该算法是在C + +实现:
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]);
}
本文详细介绍了一种简单直观的排序算法——选择排序,并通过实例演示了其工作原理。选择排序通过不断寻找未排序部分的最小元素并将其放到已排序序列的末尾来实现排序过程。
2497

被折叠的 条评论
为什么被折叠?



