简体   繁体   English

c中的升序和降序

[英]ascending and descending order in c

I am a beginner in programming languages like c,c++ and java I really need someone to guide me on this one So the problem is: This code, I wrote on borland c++我是 c、c++ 和 java 等编程语言的初学者我真的需要有人指导我所以问题是:这段代码,我在 borland c++ 上写的

1) 1)

for (i = 0; i < n; i++)
{
    for (j = i; j < n; j++)
    {
        if (number[i] > number[j])
        {
        a =  number[i];
        number[i] = number[j];
        number[j] = a;
        }
    }
} 

2) 2)

for (i = 0; i < n; i++)
{
    for (j = 0; j < n; j++)
    {
        if (number[i] > number[j])
        {
        a =  number[i];
        number[i] = number[j];
        number[j] = a;
        }
   }
} 

In the first code the logic in the inner for loop j=i will sort the numbers in ascending order,in the second code the logic in the inner for loop j=0 will sort the numbers in descending order.在第一个代码中,内部 for 循环 j=i 中的逻辑将按升序对数字进行排序,在第二个代码中,内部 for 循环中的逻辑 j=0 将按降序对数字进行排序。

Now my question is: why do the logic j=i sorts the number in ascending order and why the logic j=0 sorts the number in descending order, can someone explain the working concepts and the difference between the logic j=i and j=0?现在我的问题是:为什么逻辑 j=i 将数字按升序排序,为什么逻辑 j=0 将数字按降序排序,有人可以解释工作概念以及逻辑 j=i 和 j= 之间的区别吗? 0?

What happens in the second code differently from the first is that the loop starts sorting the numbers in ascending order (just like the first code) but because the second (inner loop) compares the current number with the already sorted numbers in the beginning (which are the smallest) swaps places.第二个代码与第一个代码不同的是,循环开始按升序对数字进行排序(就像第一个代码一样),但因为第二个(内部循环)将当前数字与开头已经排序的数字进行比较(这是最小的)交换位置。 Thus we end up with the largest numbers first.因此,我们首先得到最大的数字。 Look at it as if the first code is the first step of the second code: first put the numbers in order and then in descending order.看它好像第一个代码是第二个代码的第一步:先把数字按顺序排列,然后按降序排列。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM