C语言 对三个数字进行排序的更简单方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4367745/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 07:19:08  来源:igfitidea点击:

Simpler way of sorting three numbers

c

提问by newbie

Is there a simpler and better way to solve this problem because

有没有更简单更好的方法来解决这个问题,因为

  1. I used too many variables.
  2. I used so many if elsestatements
  3. I did this using the brute force method
  1. 我使用了太多变量。
  2. 我用了这么多if else语句
  3. 我使用蛮力方法做到了这一点

Write a program that receives three integers as input and outputs the numbers in increasing order.
Do not use loop / array.

编写一个程序,接收三个整数作为输入并按升序输出这些数字。
不要使用循环/数组。

#include <stdio.h>
main(){
   int no1;
   int no2;
   int no3;
   int sto;
   int hi;
   int lo;

   printf("Enter No. 1: ");
   scanf("%d", &no1);
   printf("Enter No. 2: ");
   scanf("%d", &no2);         
   printf("Enter No. 3: ");
   scanf("%d", &no3);

   if (no1>no2) {   
      sto=no1;    
      lo=no2;   
   } else {
      sto=no2;  
      lo=no1;  
   } 
   if (sto>no3) { 
      hi=sto;    
      if(lo>no3){         
         sto=lo;                
         lo=no3;
      }else {
         sto=no3;      
      }         
   }else hi=no3; 

   printf("LOWEST %d\n", lo);
   printf("MIDDLE %d\n", sto);
   printf("HIGHEST %d\n", hi);  

   getch(); 
}    

回答by Petar Minchev

if (a > c)
   swap(a, c);

if (a > b)
   swap(a, b);

//Now the smallest element is the 1st one. Just check the 2nd and 3rd

if (b > c)
   swap(b, c);

Note: Swap changes the values of two variables.

注意:交换会更改两个变量的值。

回答by NPE

Call the three variables x, y, and z, then:

调用三个变量xy、 和z,然后:

if (x > y) swap(x, y);
if (y > z) swap(y, z)
if (x > y) swap(x, y);

Writing the swapfunction is left as an exercise for the reader. Hint: you may have to use pointers.

编写swap函数留给读者作为练习。提示:您可能必须使用指针。

回答by Vovanium

#include <stdio.h>
#define min(a,b) ((a)<(b)?(a):(b))
#define max(a,b) ((a)>(b)?(a):(b))
int main(){
   int a, b, c;
   int hi;
   int lo;

   printf("Enter No. 1: ");
   scanf("%d", &a);
   printf("Enter No. 2: ");
   scanf("%d", &b);         
   printf("Enter No. 3: ");
   scanf("%d", &c);

   lo = min(min(a, b), c);
   hi = max(max(a, b), c);
   printf("LOWEST %d\n", lo);
   printf("MIDDLE %d\n", a+b+c-lo-hi);
   printf("HIGHEST %d\n", hi);  

   getchar(); 
}    

回答by gdj

Hint: if you have 3 numbers, a, b, and c, min(a, min(b, c)) is the smallest, max(a, max(b, c)) is the largest, and given the smallest and largest numbers, it should be easy to find the third one.

提示:如果你有 3 个数字,a、b 和 c,min(a, min(b, c)) 是最小的,max(a, max(b, c)) 是最大的,并且给定的最小和最大的数,应该很容易找到第三个。

回答by Lou Franco

Yes, there is a much better way, but you need to use loops and arrays.

是的,有更好的方法,但您需要使用循环和数组。

Probably, for an introductory class, your answer is the answer they are looking for.

可能,对于入门课程,您的答案就是他们正在寻找的答案。

There are ways to get looping with for/while (recursion, goto, etc). And ways to get something like an array without indexing (int *ptr = malloc (3 * sizeof(int)), and then index with *(ptr+index)). But, I find it hard to think that that's what they want.

有多种方法可以使用 for/while(递归、goto 等)进行循环。以及在没有索引的情况下获得类似数组的方法 ( int *ptr = malloc (3 * sizeof(int)),然后用 索引*(ptr+index))。但是,我发现很难认为这就是他们想要的。

回答by David C. Rankin

To find the min, midand maxof 3 values, you can use the ternaryoperator. You can either do all your work within the main body of your code, or you can separate the minof3, midof3and maxof3calculations into reusable functions.

要找到3 个值的minmidmax,您可以使用三元运算符。您可以在代码主体中完成所有工作,也可以将minof3,midof3maxof3计算分离为可重用的函数。

In the case of minand maxyou simply make 2 out of 3 possible comparisons, and then return a comparison of the results. In the case of mid, you do the same, but compute the min and max of the 3 values, and then check all 3 against minand maxin order to find the value that is neither the minor max. (you can do this part in the main body of your code without an additional function by declaring the min and max values as variables and doing the elimination there).

minmax的情况下,您只需从 3 个可能的比较中进行 2 个,然后返回结果的比较。在的情况下,中期,你做的一样,但计算3个值的最小值和最大值,然后检查所有3对最大值,以便找到既不是值最小最大。(您可以通过将最小值和最大值声明为变量并在那里进行消除来在代码的主体中完成这部分工作,而无需额外的函数)。

Putting the pieces together, you could do something similar to the following, which takes the first 3 arguments as the values to sort (or uses defaults of 99, 231, 8if a needed value isn't specified)

将各个部分放在一起,您可以执行类似于以下操作的操作,它将前 3 个参数作为要排序的值(99, 231, 8如果未指定所需值,则使用默认值)

#include <stdio.h>
#include <stdlib.h>

/** direct ternary comparison of 3 values */
long minof3 (long a, long b, long c) {
    long x = a < b ? a : b,
         y = a < c ? a : c;
    return x < y ? x : y;
}

long maxof3 (long a, long b, long c) {
    long x = a > b ? a : b,
         y = a > c ? a : c;
    return x > y ? x : y;
}

long midof3 (long a, long b, long c) {
    long x = minof3 (a, b, c),
         z = maxof3 (a, b, c),
         y = a == x ? b : a;
    return y == z ? c : y;
}

int main (int argc, char **argv) {

    long x = argc > 1 ? strtol (argv[1], NULL, 10) : 99,
         y = argc > 2 ? strtol (argv[2], NULL, 10) : 231,
         z = argc > 3 ? strtol (argv[3], NULL, 10) : 8;

    printf ("\n sorted values : %ld, %ld, %ld\n",
            minof3 (x, y, z), midof3 (x, y, z), maxof3 (x, y, z));

    return 0;
}

Example Use/Output

示例使用/输出

$ ./bin/sort3
 sorted values : 8, 99, 231

$ ./bin/sort3 -23 -281 1031
 sorted values : -281, -23, 1031

(yes, I know this is an old post, but given the recent comment about code hidden behind the swapfunction, a full example was in order).

(是的,我知道这是一篇旧帖子,但鉴于最近关于隐藏在swap函数后面的代码的评论,一个完整的例子是有序的)。

回答by glopes

If you want to sort the values into new external variables, you can actually do the swaps without temporaries:

如果要将值排序为新的外部变量,则实际上可以在没有临时变量的情况下进行交换:

void sort(int a, int b, int c, int *min, int *mid, int *max) {
    min = a;
    mid = b;
    max = c;
    if (min > mid) { mid = a; min = b; }
    if (mid > max)
    {
        max = mid;
        mid = c;
        if (min > mid)
        {
            mid = min;
            min = c;
        }
    }
}

This works because the last swap test is really only needed if the second test succeeds (otherwise it will simply be a repetition of the first test, which will fail by definition since we already sorted those variables).

这是有效的,因为最后一次交换测试实际上只有在第二次测试成功时才需要(否则它将只是重复第一次测试,因为我们已经对这些变量进行了排序,因此根据定义将失败)。

Because of this, we can track the assignments of each of the original variables and avoid swap locals.

因此,我们可以跟踪每个原始变量的分配并避免交换局部变量。

回答by Ronald Souza

This answer assumes that "simpler and better"translates to "a short code that minimizes the number of conditional tests, variables and assigment operations". Also, it assumes that upon receiveing the values your goal is simply to output them in ascending order, as you stated in your description:

这个答案假设“更简单和更好”转化为“将条件测试、变量和赋值操作的数量最小化的短代码”。此外,它假设在接收值时,您的目标只是按升序输出它们,如您在描述中所述:

Write a program that (...) outputs the numbers in increasing order

编写一个程序,(...) 按递增顺序输出数字

That said, the following code performs only 2 (best case) to 3 (worst case) conditional tests, and uses no assignment operations nor any extra variables:

也就是说,以下代码仅执行 2(最佳情况)到 3(最坏情况)条件测试,并且不使用赋值操作或任何额外变量:

#include <stdio.h>
void echo(int _1st, int _2nd, int _3rd) { printf("%d %d %d", _1st, _2nd, _3rd); }
void echoFromSequence(int pivot, int x, int y) {
    (pivot < y) ? ((x < y) ? echo(pivot, x, y) : echo(pivot, y, x)) : echo(y, pivot, x);
}
void printSorted(int a, int b, int c) {
    (a < b) ? echoFromSequence(a, b, c) : echoFromSequence(b, a, c);
}

Basic call(scanf()stuff avoided for simplicity):

基本调用scanf()为简单起见避免使用):

int main() {
    printSorted(2,3,1); //Output: 1 2 3
}

回答by cdlane

A compact solution sans magicswap()function, that dances around intoverflow, and abuses arrays:

一个没有魔法swap()函数的紧凑解决方案,它在int溢出周围跳舞,并滥用数组:

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char **argv) {

    int a = atoi(argv[1]);
    int b = atoi(argv[2]);
    int c = atoi(argv[3]);

    int ab[] = {a, b}, bc[] = {b, c};
    int smaller[] = {ab[a > b], bc[b > c]}, larger[] = {ab[a < b], bc[b < c]};
    int smallest = smaller[a > c], largest = larger[a < c];
    int middle = (a - smallest) + (b - largest) + c;

    printf("%d, %d, %d\n", smallest, middle, largest);

    return 0;
}

USAGE

用法

> ./a.out 2147483647 2147483645 2147483646
2147483645, 2147483646, 2147483647
> 

回答by Arun Kumar

I was attempting to solve the same problem today. Could make this compact version of code without using any temporary variables; loops; library functions like swap, sort, max, min, etc. The code uses only if statements and makes continuous mutations in the hierarchy until all possibilities are checked.

我今天试图解决同样的问题。可以在不使用任何临时变量的情况下制作这个紧凑版本的代码;循环;库函数,如交换、排序、最大值、最小值等。代码仅使用 if 语句并在层次结构中进行连续更改,直到检查所有可能性。

int main()
{
  int a, b, c; //User inputs stored in these three variables
  int first, second, third; //These three variables will store the sorted numbers in sequence
  std::cout<<"Please enter three integers : "; //User input prompt
  std::cin>>a>>b>>c;

  first = a; //Initially assuming number 'a' is smallest
  if (b <= a && b <= c) first = b; //Checking whether b is smallest
  if (c <= a && c <= b) first = c; //Checking whether c is smallest
  if (((a >= b && a <= c) || (a >= c && a <= b))) second = a; //Checking if a is middle number
  if (((b >= a && b <= c) || (b >= c && b <= a))) second = b; //Checking if b is middle number
  if (((c >= a && c <= b) || (c >= b && b <= a))) second = c; //Checking if c is middle number
  if (a >= b && a >= c) third = a; //Checking if a is the greatest
  if (b >= c && b >= a) third = b; //Checking if b is the greatest
  if (c >= a && c >= b) third = c; //Checking if c is the greatest

  std::cout<<"The numbers in ascending order are : "<<first<<", "<<second<<", "<<third<<std::endl;
}