一维整数数组排序

本文介绍了Java中的数组操作,包括随机生成数组、数组作为方法参数和返回值、以及selectSort和merge排序算法的实现。代码展示了如何创建数组、调用函数并处理数组内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、数组特性,随机存取结构,数组扩容问题

2、数组作为方法的参数和返回值,传递引用


public class HelloWorld {
  public static int[] random(int n,int range){
    int [] x = new int[n];
    while(n>0)  x[--n]=(int)(Math.random()*range);
    return x;
  }
  public static int[] random(){
    return random(10,100);
  }
  public static void print(final int[] x){
    System.out.print("{");
    if(x.length>0)  System.out.print(x[0]);
    for(int i=0;i<x.length;i++)  System.out.print(","+x[i]);
    System.out.println("}");
  }
  public static void selectSort(int [] x){
    for(int i=0;i< x.length;i++){
      int min=i;
      for(int j=i;j<x.length;j++)
        if(x[j] < x[min]) min=j;
        if(i !=min){
          int temp=x[i];
          x[i]=x[min];
          x[min]=temp;
      }
    }
  }
  public static int[] merge(int[] x,int [] y){
    int z[] = new int [x.length+y.length],i=0,j=0,k=0;
    while(i<x.length && j<y.length)
      if(x[i] < y[j]) z[k++]=x[i++];
    else z[k++]=y[j++];
    while (i<x.length)  z[k++]=x[i++];
    while(j<y.length)  z[k++]=y[j++];
    return z;
  }

  public static void main(String[] args) {
    int n1=7,range1=100;
    int[] value1=random(n1,range1),value2=random(6,100);
    System.out.print("value1:"); print(value1);
    System.out.print("value2:"); print(value2);
    selectSort(value1); selectSort(value2);
    System.out.print("sorted value1:"); print(value1);
    System.out.print("sorted value2:"); print(value2);
    System.out.print("merge:"); print(merge(value1,value2));
  }
}

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值