您的位置:首页 > 其它

将一整数序列按奇数在前,偶数在后的顺序重新排放,并要求奇偶两部分分别有序。

2005-01-22 02:10 771 查看
将一整数序列按奇数在前,偶数在后的顺序重新排放,并要求奇偶两部分分别有序。编写一函数实现。

#include <stdio.h>
#define N 15

void sort(int *,int);
void swap(int *, int *);

int main()
{
      int int_array
= {0,10,9,8,7,6,5,4,3,2,1,11,15,13,0} ;
      int i;

      sort(int_array,N);
      for (i=0;i<N;i++)
        printf("%5d/n",int_array[i]);

      return 0;
}

/* define the function sort()     */
/* parameter: int * , int         */
/* return: void                   */
/* function: rank a integer array */
void sort(int *ptr,int n)
{
    int i,j;  /* loop variable */
    /* rank odd number */
    for (i=0;i<n;i++)
      for (j=n-1;j>i;j--)
        if ( ptr[j] != 0 && ptr[j]%2 ==1 )
          if ( (ptr[j]%2+ptr[j-1]%2 != 2) || (ptr[j]<ptr[j-1]) )
            swap(&ptr[j],&ptr[j-1]);
    /* rank even number */
    for (i=n-1;i>0;i--)
      for (j=0;j<i;j++)
        if ( ptr[j] != 0 && ptr[j]%2 ==0 )
          if ( (ptr[j]%2+ptr[j+1]%2 != 2) || (ptr[j]>ptr[j+1]) )
            swap(&ptr[j],&ptr[j+1]);
    /* rank result: odd number before zero, even number after zero, */
    /*              there are form small to big!                    */
}

/* define the function swap() */
/* parameter: int * ,int *    */
/* return: void               */
/* function: swap two numbers */
void swap(int *fst, int *sec)
{
   int temp;
   temp = *fst;
   *fst = *sec;
   *sec = temp;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  function integer numbers ini
相关文章推荐