给定整型数组,排序,要求奇数在前,偶数在后,求更简单方法
程序代码:
#include<iostream> void Sort(int *nums,int length); void Sort(int *nums,int length) { int count_p=0; for(int i=0;i<length;i++) { if(nums[i]%2!=0)count_p++; } std::cout<<count_p<<std::endl; //排奇偶 for(int i=0,j=0;i<count_p;i++) { if(nums[i]%2!=0);//奇,跳过 else { for(j=i+1;j<length,nums[j]%2==0;j++); int temp=nums[i]; nums[i]=nums[j]; nums[j]=temp; } } for(int i=0;i<count_p;i++) { for(int j=i+1;j<count_p;j++) { if(nums[i]>nums[j]) { int temp=nums[i]; nums[i]=nums[j]; nums[j]=temp; } } } for(int i=count_p;i<length;i++) { for(int j=i+1;j<length;j++) { if(nums[i]>nums[j]) { int temp=nums[i]; nums[i]=nums[j]; nums[j]=temp; } } } } int main() { int a[10]={22,8,7,20,5,4,3,9,1,31}; Sort(a,10); for(int i=0;i<10;i++)std::cout<<a[i]<<"\t"; std::cout<<std::endl; return 0; }