值已被互换

有许多不同的案件中,数组排序的可能是有用的。算法(如搜索看看一些存在于一个阵列)通常可以变得更简单和/或更有效时,输入的数据进行排序。此外,排序是非常有用的可读性,如当打印列表按字母顺序排列的名字。

排序通常是通过反复比较的数组元素对进行的,和交换他们如果他们满足一些标准。为了在这些元素进行比较根据不同的排序算法,与标准取决于列表将被排序(升序或降序)。交换两个元素,我们可以使用C++标准库函数的swap()。交换算法在头文件中定义,并在std命名空间中的生活。

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <algorithm> // for swap
#include <iostream>
 
int main()
{
    using namespace std;
 
    int x = 2;
    int y = 4;
    cout << "Before swap: x = " << x << ", y = " << y << endl;
    swap(x, y); // swap also lives in std namespace
    cout << "After swap:  x = " << x << ", y = " << y << endl;
}

注意,交换后,x和y的值已被互换!

选择排序

有许多方法可以对数组进行排序。选择排序可能是理解最简单的排序,使这一教学很好的候选人,即使它是一个缓慢的种类。

选择排序执行以下步骤:

1)开始在指数0,搜索找到的最小值,整个数组

2)交换发现索引0处的值的最小值

3)重复步骤1和2从下一个指数

换句话说,我们要在阵列中找到最小的元素,并把它放在第一位。然后我们要找到下一个最小的元素,并把它放在第二位。这个过程将重复进行,直到我们跑出去的元素。

下面是一个例子,该算法工作的5要素。让我们开始与样品阵列:

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]);
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值