从下一个指数

注意,交换后,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]);
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值