C++算法恢复训练之选择排序

选择排序是一种简单的排序算法,它的思想是每次从待排序的序列中选出最小的元素,将其放在序列的起始位置,然后再从剩余的元素中选出最小的元素,放在已排序部分的末尾,直到整个序列都有序。

下面是一个用 C++ 实现的选择排序的例子:

#include <iostream>
#include <vector>

using namespace std;

void selectionSort(vector<int>& array)
{
    
    
    const auto n = array.size();
    if (n < 2)
    {
    
    
        return;
    }

    for (unsigned int i = 0; i < n - 1; ++i)
    {
    
    
        // Find the min value's index
        unsigned int minIndex = i;
        for (unsigned int j = i + 1; j < n; ++j)
        {
    
    
            minIndex = array[j] < array[minIndex] ? j : minIndex;
        }

        // Swap
        if (minIndex != i)
        {
    
    
            const int temp = array[i];
            array[i] = array[minIndex];
            array[minIndex] = temp;
        }
    }
}

int main(int argc, char* argv[])
{
    
    
    // Create an array to test sort method
    vector<int> array = {
    
    2, 3, 4, 0, 7};

    cout << "Before sorting: ";
    for (int i = 0; i < array.size(); ++i)
    {
    
    
        cout << array[i] << " ";
    }
    cout << endl;

    selectionSort(array);

    cout << "After sorting: ";
    for (int i = 0; i < array.size(); ++i)
    {
    
    
        cout << array[i] << " ";
    }
    cout << endl;

    return 0;
}

在这个例子中,我们定义了一个名为 selectionSort 的函数来实现选择排序。在函数中,我们使用两个嵌套的循环来遍历数组。外层循环控制需要遍历的次数,内层循环找到未排序部分中最小的元素,并将其索引存储在 min_index 变量中。然后,我们将最小的元素和第 i 个元素交换位置,将其放在已排序部分的末尾。最后,我们在主函数中调用 selectionSort 函数对数组进行排序,并输出排序后的结果。

对于选择排序,它需要进行 n − 1 n-1 n1 轮排序,每轮排序需要比较 n − i n-i ni 次,因此总的比较次数是一个等差数列

( n − 1 ) + ( n − 2 ) + . . . + 2 + 1 = n + n ( n − 1 ) 2 (n-1) + (n-2) + ... + 2 + 1 = n + \frac{n(n-1)}{2} (n1)+(n2)+...+2+1=n+2n(n1)

O ( n 2 ) O(n^2) O(n2)。另外,由于选择排序是原地排序算法,因此它的空间复杂度为 O ( 1 ) O(1) O(1)

猜你喜欢

转载自blog.csdn.net/xcinkey/article/details/129920053