首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

自学编程003 数组声明与排序

学会数组的声明方法。

并写一段数组反转的代码。

package qqq;

public class HelloWorld {

public static void main(String[] args) { int[] a = new int[10];// 声明数组,长度10 System.out.println("生成一个随机数组,数字顺序如下:"); for(int i = 0; i < a.length; i++) { a[i] = (int)(Math.random()*100);// 为数组的每一位随机赋予一个数值 System.out.printf("%d ",a[i]);// 并将整个数组打印出来 } System.out.println("\n翻转数组,结果如下:"); int[] b = new int[10];// 重新声明一个同样长度的数组,用来存放翻转后的数组 for (int i = 0; i < b.length; i++) { b[i] = a[a.length - (i + 1)];// 将原来数组从最后一位开始,所有的数值全部按顺序输入新的数组 System.out.printf("%d ",b[i]);// 将他们打印出来

} } }

随机生成一段整数数组,并用选择排序,从小到大排列:

package qqq;

public class HelloWorld {

public static void main(String[] args) { int[] a = new int[10];// 声明数组,长度10 System.out.println("生成一个随机数组,数字顺序如下:"); for(int i = 0; i < a.length; i++) { a[i] = (int)(Math.random()*100);// 为数组的每一位随机赋予一个数值 System.out.printf("%d ",a[i]);// 并将整个数组打印出来 } for (int i = 0; i < a.length - 1; i++) { for (int j = i+1; j < a.length; j++) { if (a[i] > a[j]) { int temp = a[i]; a[i] = a[j]; a[j] = temp; } } }// 将数组按照选择排序从小到大排列 System.out.println("\n经过选择排序,数字从小到大顺序如下:"); for (int i = 0; i < a.length; i++) { System.out.printf("%d ",a[i]); } } }

随机生成一段整数数组,并用冒泡排序,从小到大排列:

package qqq;

public class HelloWorld {

public static void main(String[] args) { int[] a = new int[10];// 声明数组,长度10 System.out.println("生成一个随机数组,数字顺序如下:"); for(int i = 0; i < a.length; i++) { a[i] = (int)(Math.random()*100);// 为数组的每一位随机赋予一个数值 System.out.printf("%d ",a[i]);// 并将整个数组打印出来 } for (int i = 0; i < a.length - 1; i++) { for (int j = 0; j < a.length - i - 1; j++) { if (a[j] > a[j+1]) { int temp = a[j+1]; a[j+1] = a[j]; a[j] = temp; } } }

// 将数组按照冒泡排序从小到大排列 System.out.println("\n经过冒泡排序,数字从小到大顺序如下:"); for (int i = 0; i < a.length; i++) { System.out.printf("%d ",a[i]); } } }

用增强型for循环,在一个随机数组中找到最大的数字:

package qqq;

public class HelloWorld {

public static void main(String[] args) { int[] a = new int[10];// 声明数组,长度10 System.out.println("生成一个随机数组,数字顺序如下:"); for(int i = 0; i < a.length; i++) { a[i] = (int)(Math.random()*100);// 为数组的每一位随机赋予一个数值 System.out.printf("%d ",a[i]);// 并将整个数组打印出来 } int max = -1; for (int i : a) { if (i > max) { max = i; } } System.out.printf("\n找到数组中最大的数字如下:%d",max);

} }

  • 发表于:
  • 原文链接https://page.om.qq.com/page/O-NxXQXQhZgeNjEGyeNVL4oQ0
  • 腾讯「腾讯云开发者社区」是腾讯内容开放平台帐号(企鹅号)传播渠道之一,根据《腾讯内容开放平台服务协议》转载发布内容。
  • 如有侵权,请联系 cloudcommunity@tencent.com 删除。

扫码

添加站长 进交流群

领取专属 10元无门槛券

私享最新 技术干货

扫码加入开发者社群
领券