首页 > 解决方案 > 数组是如何排序的

问题描述

假设我们有一个长度为 的整数数组n。我们需要一个函数f(arr, n),它返回一个介于-100%和之间的数字+100%。结果越接近+100%,表示升序排列的数组越多;并且结果越接近-100%,降序排列的数组越多。如果数组完全是随机顺序,结果应该接近0%.

到目前为止,这是我的实现:

long map(long x, long in_min, long in_max, long out_min, long out_max)
{
    return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}

int f(int arr[], int n) {
    int p = 0;

    for (int i = 0; i < n - 1; i++) {
        int a = arr[i];
        int b = arr[i + 1];

        if (a != b) {
            bool asc_check = a < b;
            bool desc_check = a > b;

            if (asc_check && !desc_check)
                p++;

            else if (!asc_check && desc_check)
                p--;
        }
    }

    return map(p, -(n - 1), n - 1, -100, 100);
}

我怀疑我的代码是否准确。请帮助我编写正确的实现。

谢谢!

标签: c++arraysalgorithmsorting

解决方案


可以使用 STL 库在 C++ 中提供的排序类


推荐阅读