找到三个整数中最大的一个的最有效方法

发布于 2024-08-21 00:55:53 字数 275 浏览 6 评论 0 原文

下面是我的伪代码。

function highest(i, j, k)
{
  if(i > j && i > k)
  {
    return i;
  }
  else if (j > k)
  {
    return j;
  }
  else
  {
    return k;
  }
}

我认为这是可行的,但这是 C++ 中最有效的方法吗?

Below is my pseudo code.

function highest(i, j, k)
{
  if(i > j && i > k)
  {
    return i;
  }
  else if (j > k)
  {
    return j;
  }
  else
  {
    return k;
  }
}

I think that works, but is that the most efficient way in C++?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(17

铃予 2024-08-28 00:55:53

要找到最大的整数,您需要查看正好 3 个整数,不多也不少。您正在查看 6 个和 3 个比较。您应该能够通过 3 次和 2 次比较来完成。

int ret = max(i,j);
ret = max(ret, k);
return ret;

To find the greatest you need to look at exactly 3 ints, no more no less. You're looking at 6 with 3 compares. You should be able to do it in 3 and 2 compares.

int ret = max(i,j);
ret = max(ret, k);
return ret;
伴我心暖 2024-08-28 00:55:53

伪代码:

result = i
if j > result:
  result = j
if k > result:
  result = k
return result

Pseudocode:

result = i
if j > result:
  result = j
if k > result:
  result = k
return result
与风相奔跑 2024-08-28 00:55:53

两次比较怎么样

return i > j? (i > k? i: k): (j > k? j: k);

,不使用瞬态临时堆栈变量......

How about

return i > j? (i > k? i: k): (j > k? j: k);

two comparisons, no use of transient temporary stack variables...

终陌 2024-08-28 00:55:53

您当前的方法:
http://ideone.com/JZEqZTlj (0.40s)

Chris 的解决方案:

int ret = max(i,j);
ret = max(ret, k);
return ret;

http://ideone.com/hlnl7QZX (0.39s)

Ignacio Vazquez-Abrams 的解决方案:

result = i;
if (j > result)
  result = j;
if (k > result)
  result = k;
return result;

http://ideone.com/JKbtkgXi (0.40s)

和 Charles Bretana 的:

return i > j? (i > k? i: k): (j > k? j: k);

http ://ideone.com/kyl0SpUZ (0.40s)

在这些测试中,所有解决方案的执行时间与其他解决方案的执行时间相差不到 3%。您尝试优化的代码实际上非常短。即使您能够从中挤出 1 条指令,它也不可能对整个程序产生巨大的影响(现代编译器可能会捕获这个小的优化)。把时间花在别处吧。

编辑:更新了测试,结果发现它仍在优化之前的部分内容。希望不再是这样了。

Your current method:
http://ideone.com/JZEqZTlj (0.40s)

Chris's solution:

int ret = max(i,j);
ret = max(ret, k);
return ret;

http://ideone.com/hlnl7QZX (0.39s)

Solution by Ignacio Vazquez-Abrams:

result = i;
if (j > result)
  result = j;
if (k > result)
  result = k;
return result;

http://ideone.com/JKbtkgXi (0.40s)

And Charles Bretana's:

return i > j? (i > k? i: k): (j > k? j: k);

http://ideone.com/kyl0SpUZ (0.40s)

Of those tests, all the solutions take within 3% the amount of time to execute as the others. The code you are trying to optimize is extremely short as it is. Even if you're able to squeeze 1 instruction out of it, it's not likely to make a huge difference across the entirety of your program (modern compilers might catch that small optimization). Spend your time elsewhere.

EDIT: Updated the tests, turns out it was still optimizing parts of it out before. Hopefully it's not anymore.

毅然前行 2024-08-28 00:55:53

对于这样的问题,了解优化编译器正在做什么以及硬件上可用的内容是无可替代的。如果您拥有的基本工具是二进制比较或二进制最大值,则两次比较或最大值都是必要且充分的。

我更喜欢 Ignacio 的解决方案:

result = i;
if (j > result)
  result = j;
if (k > result)
  result = k;
return result;

因为在常见的现代 Intel 硬件上,编译器会发现非常容易发出两个比较和两个 cmov 指令,这会给 I-cache 带来更小的负载和更少的压力在分支预测器上比在条件分支上。 (此外,代码清晰易读。)如果您使用的是 x86-64,编译器甚至会将所有内容保存在寄存器中。

请注意,您将很难将此代码嵌入到您的选择会产生影响的程序中......

For a question like this, there is no substitute for knowing just what your optimizing compiler is doing and just what's available on the hardware. If the fundamental tool you have is binary comparison or binary max, two comparisons or max's are both necessary and sufficient.

I prefer Ignacio's solution:

result = i;
if (j > result)
  result = j;
if (k > result)
  result = k;
return result;

because on the common modern Intel hardware, the compiler will find it extremely easy to emit just two comparisons and two cmov instructions, which place a smaller load on the I-cache and less stress on the branch predictor than conditional branches. (Also, the code is clear and easy to read.) If you are using x86-64, the compiler will even keep everything in registers.

Note you are going to be hard pressed to embed this code into a program where your choice makes a difference...

说谎友 2024-08-28 00:55:53

我喜欢将消除条件跳转作为一种智力练习。我不知道这是否对性能有任何可测量的影响:)

#include <iostream>
#include <limits>

inline int max(int a, int b)
{
    int difference = a - b;
    int b_greater = difference >> std::numeric_limits<int>::digits;
    return a - (difference & b_greater);
}

int max(int a, int b, int c)
{
    return max(max(a, b), c);
}

int main()
{
    std::cout << max(1, 2, 3) << std::endl;
    std::cout << max(1, 3, 2) << std::endl;
    std::cout << max(2, 1, 3) << std::endl;
    std::cout << max(2, 3, 1) << std::endl;
    std::cout << max(3, 1, 2) << std::endl;
    std::cout << max(3, 2, 1) << std::endl;
}

这个小玩意只是为了好玩,cmov 解决方案可能要快得多。

I like to eliminate conditional jumps as an intellectual exercise. Whether this has any measurable effect on performance I have no idea though :)

#include <iostream>
#include <limits>

inline int max(int a, int b)
{
    int difference = a - b;
    int b_greater = difference >> std::numeric_limits<int>::digits;
    return a - (difference & b_greater);
}

int max(int a, int b, int c)
{
    return max(max(a, b), c);
}

int main()
{
    std::cout << max(1, 2, 3) << std::endl;
    std::cout << max(1, 3, 2) << std::endl;
    std::cout << max(2, 1, 3) << std::endl;
    std::cout << max(2, 3, 1) << std::endl;
    std::cout << max(3, 1, 2) << std::endl;
    std::cout << max(3, 2, 1) << std::endl;
}

This bit twiddling is just for fun, the cmov solution is probably a lot faster.

丢了幸福的猪 2024-08-28 00:55:53

不确定这是否是最有效的,但它可能是,而且肯定更短:

int maximum = max( max(i, j), k);

Not sure if this is the most efficient or not, but it might be, and it's definitely shorter:

int maximum = max( max(i, j), k);
咽泪装欢 2024-08-28 00:55:53

有人建议将其包含到 N2485 下的 C++ 库中。该提案很简单,因此我在下面包含了有意义的代码。显然,这假设了可变参数模板

template < typename T >
const T & max ( const T & a )
{ return a ; }

template < typename T , typename ... Args >
const T & max( const T & a , const T & b , const Args &... args )
{ return  max ( b > a ? b : a , args ...); }

There is a proposal to include this into the C++ library under N2485. The proposal is simple, so I've included the meaningful code below. Obviously, this assumes variadic templates

template < typename T >
const T & max ( const T & a )
{ return a ; }

template < typename T , typename ... Args >
const T & max( const T & a , const T & b , const Args &... args )
{ return  max ( b > a ? b : a , args ...); }
2024-08-28 00:55:53

在 C++ 中查找 2 个或更多数字的最大值或最小值的最简单方法是: -

int a = 3, b = 4, c = 5;
int maximum = max({a, b, c});

int a = 3, b = 4, c = 5;
int minimum = min({a, b, c});

您可以提供任意多个变量。

有趣的是,它的效率也令人难以置信,至少与 Ignacio Vazquez-Abrams 的解决方案(https://godbolt. org/z/j1KM97):

        mov     eax, dword ptr [rsp + 8]
        mov     ecx, dword ptr [rsp + 4]
        cmp     eax, ecx
        cmovl   eax, ecx
        mov     ecx, dword ptr [rsp]
        cmp     eax, ecx
        cmovl   eax, ecx

与 GCC 类似,而 MSVC 则将循环搞得一团糟。

The easiest way to find a maximum or minimum of 2 or more numbers in c++ is:-

int a = 3, b = 4, c = 5;
int maximum = max({a, b, c});

int a = 3, b = 4, c = 5;
int minimum = min({a, b, c});

You can give as many variables as you want.

Interestingly enough it is also incredibly efficient, at least as efficient as Ignacio Vazquez-Abrams'solution (https://godbolt.org/z/j1KM97):

        mov     eax, dword ptr [rsp + 8]
        mov     ecx, dword ptr [rsp + 4]
        cmp     eax, ecx
        cmovl   eax, ecx
        mov     ecx, dword ptr [rsp]
        cmp     eax, ecx
        cmovl   eax, ecx

Similar with GCC, while MSVC makes a mess with a loop.

溺深海 2024-08-28 00:55:53
public int maximum(int a,int b,int c){
    int max = a;
    if(b>max)
        max = b;
    if(c>max)
        max = c;
    return max;
}
public int maximum(int a,int b,int c){
    int max = a;
    if(b>max)
        max = b;
    if(c>max)
        max = c;
    return max;
}
姜生凉生 2024-08-28 00:55:53

我认为“最有效”指的是性能,尽量不浪费计算资源。但您可能指的是编写更少的代码行,或者可能是关于源代码的可读性。我在下面提供了一个示例,您可以评估您是否发现有用的内容或者您是否更喜欢收到的答案中的另一个版本。

/* Java version, whose syntax is very similar to C++. Call this program "LargestOfThreeNumbers.java" */
class LargestOfThreeNumbers{
    public static void main(String args[]){
        int x, y, z, largest;
        x = 1;
        y = 2;
        z = 3;
        largest = x;
        if(y > x){
            largest = y;
            if(z > y){
                largest = z;
            }
        }else if(z > x){
            largest = z;
        }
        System.out.println("The largest number is: " + largest);
    }
}

I think by "most efficient" you are talking about performance, trying not to waste computing resources. But you could be referring to writing fewer lines of code or maybe about the readability of your source code. I am providing an example below, and you can evaluate if you find something useful or if you prefer another version from the answers you received.

/* Java version, whose syntax is very similar to C++. Call this program "LargestOfThreeNumbers.java" */
class LargestOfThreeNumbers{
    public static void main(String args[]){
        int x, y, z, largest;
        x = 1;
        y = 2;
        z = 3;
        largest = x;
        if(y > x){
            largest = y;
            if(z > y){
                largest = z;
            }
        }else if(z > x){
            largest = z;
        }
        System.out.println("The largest number is: " + largest);
    }
}
深海夜未眠 2024-08-28 00:55:53
#include<stdio.h>
int main()
{
    int a,b,c,d,e;
    scanf("%d %d %d",&a,&b,&c);
    d=(a+b+abs(a-b))/2;
    e=(d+c+abs(c-d))/2;
    printf("%d is Max\n",e);
    return 0;
}
#include<stdio.h>
int main()
{
    int a,b,c,d,e;
    scanf("%d %d %d",&a,&b,&c);
    d=(a+b+abs(a-b))/2;
    e=(d+c+abs(c-d))/2;
    printf("%d is Max\n",e);
    return 0;
}
近箐 2024-08-28 00:55:53

我用的是这种方式,花了0.01秒

#include "iostream"
using std::cout;
using std::cin;
int main()
{
    int num1, num2, num3;
    cin>>num1>>num2>>num3;
    int cot {((num1>num2)?num1:num2)};
    int fnl {(num3>cot)?num3:cot};
    cout<<fnl;
}

或者这样

#include "iostream"

using std::cout;
using std::cin;
int main()
{
    int num1, num2, num3;
    cin>>num1>>num2>>num3;
    int cot {(((num1>num2)?num1:num2)>((num3>cot)?num3:cot)?((num1>num2)?num1:num2):((num3>cot)?num3:cot))};
    cout<<cot;
}

I Used This Way, It Took 0.01 Second

#include "iostream"
using std::cout;
using std::cin;
int main()
{
    int num1, num2, num3;
    cin>>num1>>num2>>num3;
    int cot {((num1>num2)?num1:num2)};
    int fnl {(num3>cot)?num3:cot};
    cout<<fnl;
}

Or This

#include "iostream"

using std::cout;
using std::cin;
int main()
{
    int num1, num2, num3;
    cin>>num1>>num2>>num3;
    int cot {(((num1>num2)?num1:num2)>((num3>cot)?num3:cot)?((num1>num2)?num1:num2):((num3>cot)?num3:cot))};
    cout<<cot;
}
知你几分 2024-08-28 00:55:53

找到 3 个数字中最大的数字的最有效方法是使用 max 函数。这是一个小例子:

#include <iostream>
#include <algorithm>

using namespace std;
int main() {
   int x = 3, y = 4, z = 5;
   cout << max(x, max(y, z)) << endl;
   return 0;
}

如果你有C++ 11,那么你可以这样做:

int main() {
   int x = 3, y = 4, z = 5;
   cout << std::max({x, y, z}); << endl;
   return 0;
}

如果你有兴趣使用一个函数,以便你可以轻松地多次调用它,代码如下:

using namespace std;

int test(int x, int y, int z) { //created a test function

    //return std::max({x, y, z}); //if installed C++11
    return max(x, max(y, z));
}

int main() {
    cout << test(1, 2, 3) << endl;
    cout << test(1, 3, 2) << endl;
    cout << test(1, 1, 1) << endl;
    cout << test(1, 2, 2) << endl;
    return 0;
}

The most efficient way to find the greatest among 3 numbers is by using max function. Here is a small example:

#include <iostream>
#include <algorithm>

using namespace std;
int main() {
   int x = 3, y = 4, z = 5;
   cout << max(x, max(y, z)) << endl;
   return 0;
}

If you have C++ 11, then you can do it as follow:

int main() {
   int x = 3, y = 4, z = 5;
   cout << std::max({x, y, z}); << endl;
   return 0;
}

If you are interested to use a function, so that you can call it easily multiple times, here is the code:

using namespace std;

int test(int x, int y, int z) { //created a test function

    //return std::max({x, y, z}); //if installed C++11
    return max(x, max(y, z));
}

int main() {
    cout << test(1, 2, 3) << endl;
    cout << test(1, 3, 2) << endl;
    cout << test(1, 1, 1) << endl;
    cout << test(1, 2, 2) << endl;
    return 0;
}
洛阳烟雨空心柳 2024-08-28 00:55:53

这是您可以使用的一个小功能:

int max3(int a, int b, int c=INT_MIN) {
    return max(a, max(b, c));
}

Here is a small function you can use:

int max3(int a, int b, int c=INT_MIN) {
    return max(a, max(b, c));
}

我一直都在从未离去 2024-08-28 00:55:53

在C#中找到3位数之间的最大和最小数字

static void recorrectFindSmallestNumber()
{
int x = 30, y = 22, z = 11;
if (x < y)
{
if (x < z)
{
Console.WriteLine("X is Smaller Numebr {0}.", x);
}
else
{
Console.WriteLine("z is Smaller Numebr {0}.", z);
}
}
else if (x > y)
{
if (y < z)
{
Console.WriteLine("y is Smaller number.{0}", y);
}
else
{
Console.WriteLine("z is Smaller number.{0}", z);
}
}
 else
{

}
}

=========================================== =========================

static void recorrectFindLargeNumber()
{
int x, y, z;
Console.WriteLine("Enter the first number:");
x = int.Parse(Console.ReadLine());
Console.WriteLine("Enter the second number:");
y = int.Parse(Console.ReadLine());
Console.WriteLine("Enter the third nuumnber:");
z = int.Parse(Console.ReadLine());
if (x > y)
{
if (x > z)
{
Console.WriteLine("X is Greater numbaer: {0}.", x);
}
else
{
Console.WriteLine("Z is greatest number: {0}.", z);
}
}
else if (x < y)
{
if (y > z)
{
Console.WriteLine("y is Greater Number: {0}", y);
}
else 
{
Console.WriteLine("Z is Greater Number; {0}", z);                
}
}
else
{
                
}
}

In C# finding the greatest and smallest number between 3 digit

static void recorrectFindSmallestNumber()
{
int x = 30, y = 22, z = 11;
if (x < y)
{
if (x < z)
{
Console.WriteLine("X is Smaller Numebr {0}.", x);
}
else
{
Console.WriteLine("z is Smaller Numebr {0}.", z);
}
}
else if (x > y)
{
if (y < z)
{
Console.WriteLine("y is Smaller number.{0}", y);
}
else
{
Console.WriteLine("z is Smaller number.{0}", z);
}
}
 else
{

}
}

=================================================================

static void recorrectFindLargeNumber()
{
int x, y, z;
Console.WriteLine("Enter the first number:");
x = int.Parse(Console.ReadLine());
Console.WriteLine("Enter the second number:");
y = int.Parse(Console.ReadLine());
Console.WriteLine("Enter the third nuumnber:");
z = int.Parse(Console.ReadLine());
if (x > y)
{
if (x > z)
{
Console.WriteLine("X is Greater numbaer: {0}.", x);
}
else
{
Console.WriteLine("Z is greatest number: {0}.", z);
}
}
else if (x < y)
{
if (y > z)
{
Console.WriteLine("y is Greater Number: {0}", y);
}
else 
{
Console.WriteLine("Z is Greater Number; {0}", z);                
}
}
else
{
                
}
}
凶凌 2024-08-28 00:55:53
#include<iostream>
#include<cmath>
using namespace std;
int main()
{
int num1,num2,num3,maximum;

cout<<"Enter 3 numbers one by one "<<endl;
cin>>num1;
cin>>num2;
cin>>num3;

maximum=max(max(num1,num2),num3);

cout<<"maximum of 3 numbers is "<<maximum<<endl;
}
#include<iostream>
#include<cmath>
using namespace std;
int main()
{
int num1,num2,num3,maximum;

cout<<"Enter 3 numbers one by one "<<endl;
cin>>num1;
cin>>num2;
cin>>num3;

maximum=max(max(num1,num2),num3);

cout<<"maximum of 3 numbers is "<<maximum<<endl;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文