c++ - 我将如何实现这种蛮力中值搜索算法?

标签 c++ algorithm

我正在思考这段代码如何找到 int 数组的中位数,如 this booklet 的屏幕截图所示.如我的代码所示,我一直在尝试使用 C++ 复制代码块中的代码。

我需要使用哪些基本操作?我需要更改什么才能让我的代码正常工作?

#include <iostream>
#include <algorithm>
using namespace std;

int main()
{
int A[] = {2,3,4,7,8,9,10,12,15};
int n = ( sizeof(A) / sizeof(A[0]) );
int k = (n/2);

for(int i=0; n-1; i++)
{
    int numsmaller = 0;
    int numequal = 0;
    for(int j=1; n-1; j++)
    {
        if(A[j]<A[i])
        {
            numsmaller = numsmaller + 1;
        }
        else if(A[j]=A[i])
        {
            numequal = numequal + 1;
        }
    }
    if(((numsmaller < k)&&(k<=(numsmaller + numequal))))
    {
        k = A[i];
        cout << k;
    }
}
return 0;
}
############ 固定编码######################。
#include <iostream>
#include <algorithm>
using namespace std;

int main()
{
int A[] = {2,3,4,7,8,9,10,12,15};
int n = ( sizeof(A) / sizeof(A[0]) );
int k = (n/2);

for(int i=0;i <= (n-1); i++)
{
int numsmaller = 0;
int numequal = 0;
for(int j=1;j <= (n-1); j++)
{
    if(A[j]<A[i])
    {
        numsmaller = numsmaller + 1;
    }
    else if(A[j]==A[i])
    {
        numequal = numequal + 1;
    }
}
if(((numsmaller < k)&&(k<=(numsmaller + numequal))))
{
    k = A[i];
    cout << k;
    return 0;
}
}
return 0;
}

最佳答案

虽然这个算法效率很低。为什么要用它来搜索数组?

您可能想看看 quickselect算法。它工作得更快。但如果您真的在截止日期前完成作业,您就会知道这一点。

关于c++ - 我将如何实现这种蛮力中值搜索算法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37517201/

相关文章:

c++ - 在 C++ 中读取 COM 端口数据

用于按多个条件对对象中的数组进行排序的 JavaScript 算法

algorithm - 绘制别名、像素完美的 1px 样条曲线(特别是 Catmull-Rom)

algorithm - 对列表中的相邻元素进行分组

c++ - 使用 scanf 读入 std::string

c++ - 如何找到硬件算法完全支持的最大整数?

algorithm - 在任意坐标周围找到半径为 r 的球体中的所有点

java - 基本算法的复杂性?

c++ - 返回一个带有 "return std::set<int>()"的空集 - 它为什么运行?

c++ - 在 Qt 中使用 Cuda 编译出现链接错误