java排序,随机生成一个数组,对其进行排序,偶数在前奇数在后,偶数从小到大排,奇数从大到小排

package demo01;


import java.util.Random;


/**
 *
 * @author sunzhen
 */
public class Demo01
{


  /**
   * @param args the command line arguments
   */
  public static void main( String[] args )
  {
    Demo01 demo = new Demo01();
    int n = 10;
    int num = 100;
    int[] b = demo.arr(n, num);
    demo.prints(b);//排序前
    demo.arrSort(b);//调用排序函数
    demo.prints(b);//排序后
  }


  /**
   * 随机生成一个数组
   *
   * @param n 数组长度
   * @param num 取值范围
   * @return a 随机数组
   */
  public int[] arr( int n, int num )
  {
    Random random = new Random();
    int[] a = new int[n];
    for (int i = 0; i < a.length; i++)
    {
      int temp = random.nextInt(num);
      a[i] = temp;
    }
    return a;
  }


  /**
   * 以com()函数作为条件进行排序
   *
   * @param a 随机数组
   */
  public void arrSort( int[] a )
  {
    for (int i = 0; i < a.length; i++)
    {
      for (int j = 0; j <= i; j++)
      {
        if ( com( a[i], a[j] ))
        {
          int tem = a[i];
          a[i] = a[j];
          a[j] = tem;
        }
      }
    }
  }


  /**
   * 判断参数的奇偶、大小,决定是否交换位置
   *
   * @param a 数组中的某个值
   * @param b 数组中的某个值
   * @return
   */
  public boolean com( int a, int b )
  {
    if ((a % 2 == 0) && (b % 2 != 0))
    {
      return true;//奇数偶数交换
    }
    if ((a % 2 != 0) && (b % 2 == 0))
    {
      return false;//奇数偶数不交换
    }
    if ((a % 2 == 0) && (b % 2 == 0))
    {
      return a < b;//同为偶数小的在前
    }
    return a > b;//同为奇数大的在前
  }


  /**
   * 打印数组
   *
   * @param a 数组
   */
  public void prints( int a[] )
  {
    for (int i = 0; i < a.length; i++)
    {
      System.out.print("  " + a[i]);
    }
    System.out.println("");
  }
}
  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值