[英]I want to output 1 4 2 3 5 odd number ascending order and even numbers in descending order
I want to output odd numbers in ascending order and even numbers in descending order my code is here.我想 output 奇数按升序排列,偶数按降序排列我的代码在这里。
When I give input n=5
array 5 2 4 3 1
, I want to output 1 4 2 3 5
, but I got output 4 2 1 3 5
.当我输入
n=5
array 5 2 4 3 1
时,我想 output 1 4 2 3 5
,但我得到了 output 4 2 1 3 5
。 I don't want the position of array.我不想要数组的 position。
#include <iostream>
using namespace std;
int main()
{
int n;
cin >> n;
int arr[n];
for (int i = 0; i < n; ++i)
{
cin >> arr[i];
}
// odd number ascending order
for (int i = 0; i <= n; ++i)
{
for (int j = i + 1; j < n; ++j)
{
if (arr[i] < arr[j])
{
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
for (int i = 0; i < n; ++i)
{
if (arr[i] % 2 == 0)
{
cout << arr[i]<< " ";
}
}
// numbers in descending order
for (int i = 0; i <= n - 1; i++)
{
for (int j = i + 1; j <= n; j++)
{
if (arr[j] < arr[i])
{
int temp = arr[j];
arr[j] = arr[i];
arr[i] = temp;
}
}
if (arr[i] % 2 == 1)
{
cout << arr[i]<<" ";
}
}
return 0;
}
#include <iostream>
using namespace std;
int main()
{
int n = 5;
int left = 1, right = n - (n % 2);
for(int i = 1; i <= n; i++)
{
if(i % 2 == 0)
{
cout << right << ' ';
right-= 2;
}
else if(i % 2 == 1)
{
cout << left << ' ';
left += 2;
}
}
return 0;
}
We, beginners, should help each other.:)我们,初学者,应该互相帮助。:)
The task is not easy for such beginners as you and me.对于你我这样的初学者来说,这项任务并不容易。
I can suggest an approach based on the bubble sort method.我可以建议一种基于冒泡排序方法的方法。
Here you are.给你。
#include <iostream>
#include <utility>
template <typename UnaryPredicate>
void conditional_bubble_sort( int a[], size_t n,
UnaryPredicate &&unary_predicate,
bool order = false )
{
while ( n && !unary_predicate( *a ) )
{
++a;
--n;
}
for ( size_t i = 0, last = 0; !( n < 2 ); n = last )
{
last = 0;
for ( size_t current = 0, next = 0; next < n; current = next )
{
while ( ++next < n && !unary_predicate( a[next] ) );
if ( next != n )
{
if ( !order /* ascending */ ? a[next] < a[current] : a[current] < a[next] )
{
std::swap( a[current], a[next] );
last = next;
}
}
}
}
}
int main()
{
int a[] = { 5, 2, 4, 3, 1 };
const size_t N = sizeof( a ) / sizeof( *a );
for ( const auto &item : a )
{
std::cout << item << ' ';
}
std::cout << '\n';
conditional_bubble_sort( a, N, []( const auto &item ) { return item % 2 != 0;} );
for ( const auto &item : a )
{
std::cout << item << ' ';
}
std::cout << '\n';
conditional_bubble_sort( a, N, []( const auto &item ) { return item % 2 == 0;}, true );
for ( const auto &item : a )
{
std::cout << item << ' ';
}
std::cout << '\n';
return 0;
}
The program output is程序 output 是
5 2 4 3 1
1 2 4 3 5
1 4 2 3 5
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.