自定义排序算法c++

Custom sorting algorithm c++

我正在修补 C++,我当时想 let's make a sorting algorithm :)

我做了一些事情,但它没有对数组进行排序,而是用最大数覆盖了数组

我不知道我的错误在哪里,因为我 运行 纸上的算法(不要问)而且它是正确的。

我尝试了所有可能的修改。
有帮助吗?

#include <iostream>
#include <cstring>

using namespace std;

int main()
{
    int mn = 0, mx = 0;
    int a[] = { 4, 8, 5, 2, 6, 9, 0, 3, 1, 7 };

    for (int i = 0; i < 10; i++)
    {
        mn = a[i]; mx = a[i];
        for (int j = i; j < 10 - i; j++)
        {
            mn = min(a[j], mn);
            mx = max(a[j], mx);
        }
        swap(a[i], mn);
        swap(a[10-1-i], mx);
    }

    for(int i=0;i<10;i++)
    {
        cout<<a[i]<<" ";
    }
}

您不是在交换数组元素,而是基本上将 min/max 值写入数组中的相应位置。它们的旧值被简单地覆盖了。您需要跟踪 min/max 元素的位置并相应地交换,例如swap(a[i], a[min_pos])。此外,您可以 运行 您的外循环直到到达数组的中间,因为您在每次迭代中将两个元素放到它们的位置。

这是工作代码:

#include <iostream>
#include <cstring>

using namespace std;

int main()
{
    int mn = 0, mx = 0;
    int a[] = { 4, 8, 5, 2, 6, 9, 0, 3, 1, 7 };

    for (int i = 0; i < 10 / 2; i++)
    {
        int min_pos = i, max_pos = i;

        for (int j = i; j < 10 - i; j++)
        {
            if (a[j] < a[min_pos]) {
                min_pos = j;
            } else if (a[j] > a[max_pos]) {
                max_pos = j;
            }
        }

        int min_val = a[min_pos];
        int max_val = a[max_pos];

        swap(a[i], a[min_pos]);
        swap(a[10-1-i], a[max_pos]);

        a[i] = min_val;
        a[10-1-i] = max_val;
    }

    for(int i=0;i<10;i++)
    {
        cout<<a[i]<<" ";
    }
}

请注意,您需要注意 'special cases',例如当 min_posmax_pos 位于间隔的末端时 - 它们将被交换两次并保持在原来的位置。