[英]C++ sorting an array in ascending order Printing
Im trying to sort an array in ascending order and print it out and Im having trouble of where to put my cout in my code.我试图按升序对数组进行排序并将其打印出来,但我在将 cout 放在代码中的位置时遇到了麻烦。
for (int k=0; k<ARRAY_SIZE; k++) {
for (int l=1; l<ARRAY_SIZE-1; l++) {
if(numbers[l] > numbers[k]) {
temp = numbers[k];
numbers[k] = numbers[l];
numbers[l] = temp;
}
cout<<numbers[k];
}
}
Remove the actual cout
and put it after the sorting loop, in a new loop删除实际
cout
并将其放在排序循环之后,在一个新循环中
for(int k = 0 ; k < ARRAY_SIZE; ++k)
cout << numbers[k] << " ";
如果要查看排序结果,则必须在新的 for 循环中打印数组
This is a program that finds the length of a number n
and converts it to an array arr
and sorts that array in ascending order.这是一个查找数字
n
的长度并将其转换为数组arr
并按升序对该数组进行排序的程序。 (possible aptitude question)
#include <iostream>
using namespace std;
int main()
{
int n,i=0,j,num,temp,len=0,arr[10]={0};
cin>>n;
num=n;
while(n!=0)
{
len++;
n/=10;
}
cout<<len<<endl;
for ( i = len; i >= 0; i--)
{
arr[i] = num%10;
num/=10;
}
for(i=1;i<=len;i++)
for(j=0;j<=len-i;j++)
{
if(arr[j]>arr[j+1])
{
temp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}
}
for(i=1;i<=len;i++)
{
cout<<arr[i]<<endl;
}
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.