1002:奇偶排序
总时间限制:1000ms 内存限制: 65536kB
描述
输入十个整数,将十个整数按升序排列输出,并且奇数在前,偶数在后。
输入
输入十个整数
输出
按照奇偶排序好的十个整数
样例输入
10 9 8 7 6 5 4 3 2 1
样例输出
1 3 5 7 9 2 4 6 8 10
思路
先遍历数组,把元素分成奇偶两部分,奇数都在左边,偶数都在右边,然后使用冒泡排序分别将左右的元素排序,输出即可。
代码
#include <iostream>
using namespace std;
//int n=10;
void Swap(int &a,int &b)
{
int tmp=a;
a=b;
b=tmp;
}
//double loop to compare from left to right, swap the biggest to the right first.
// ascending
// It's important to remember
void BubbleSort(int arr[],int beg, int en)
{
for(int i=beg;i<=en;i++) //control comparison times
{
for(int j=beg+1;j<=beg+en-i;j++) //pay attention to j's termination time
{
if(arr[j]<arr[j-1])
Swap(arr[j],arr[j-1]);
}
}
}
int main()
{
//input
int n=10;
int arr[n];
for(int i=0;i<n;i++)
cin>>arr[i];
// use pointer to separate odd and even
int left=0,right=n-1;
while(left<=right)
{
bool isLeftOdd=(arr[left]%2==1);
bool isRightEven=(arr[right]%2==0);
if(isLeftOdd)
left++;
else if(isRightEven)
right--;
else if(!isLeftOdd && !isRightEven)
Swap(arr[left++],arr[right--]);
}
//sort the odd and even numbers with bubble sort respectively
BubbleSort(arr,0,right);
BubbleSort(arr,right+1,n-1);
//output
for(int i=0;i<n;i++)
cout <<arr[i]<<' ';
return 0;
}