在c ++中以升序形式对数组进行排序 [英] Sorting an array in ascending form in c++
本文介绍了在c ++中以升序形式对数组进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试以升序形式对数组进行排序,这就是我尝试过的。我无法弄清楚我犯了哪个错误,但我得到的输出是完全垃圾。谁能解释一下我的错误在哪里?我真的被卡住了。
我得到的输出只是4,3,4。没有任何意义!
I am trying to sort an array in ascending form and this is what i tried. I cant figure out where i made the mistake but the output that i get is complete garbage. Could anyone explain me where my error could be? I am really stuck.
The output that i get is only "4,3,4". Doesnt make any sense!
#include<iostream>
using namespace std;
int main ()
{
int n[6]={5,4,5,3,5,10 };
int counter;
for(int i=0; i<5; i++)
{
for(int j = i+1; j<6; j++)
{
if(n[i+1]<n[i])
{
int temp = n[i];
n[i] = n[i+1];
n[i+1]= temp;
cout<<n[i];
}
}
}
system("pause");
}
推荐答案
cout
在错误的地方。
cout
只有在if条件为真时才会发生。
要打印已排序数组的内容,在完成所有排序后需要一个单独的循环。
因此在完成所有排序后创建一个新循环并且来自该循环的cout
。
Thecout
is in the wrong place.
Thecout
will happen only when the if condition is true.
To print the contents of the sorted array you will need a separate loop after all the sorting is done.
So create a new loop after all the sorting is done andcout
from that loop.
这篇关于在c ++中以升序形式对数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文