c++ - 数组是如何排序的
问题描述
假设我们有一个长度为 的整数数组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);
}
我怀疑我的代码是否准确。请帮助我编写正确的实现。
谢谢!
解决方案
可以使用 STL 库在 C++ 中提供的排序类
推荐阅读
- javascript - Sails - 如何知道控制器或助手是否已经结束?
- excel - 尝试使用 excel 2010 vba 解决“重命名”表
- wordpress - 在 Woocommerce 3 中自定义购物车项目删除通知
- batch-file - 如何在批处理文件中制作工作菜单?
- python - 将库依赖项注入 django 模型
- javascript - 使用 jQuery 中的一个按钮隐藏/显示 div
- r - 从字符串中提取金额
- powershell - 通过 PowerShell 清除 IE 上的 SSL 状态
- powershell - 在 foreach 循环后运行 start-process
- php - 我的密码接受大小写字母