Java数组常用方法和排序
package com.yuan; import java.util.Arrays; public class Practise1 { public static void main(String[] args){ //数组 String[] st2; st2 = new String[4]; String st3[] = {"kd", "38dj"}; String st4[] = new String[]{"123", "yui", "2k3j"}; //二维数组 int t1[][] ={{1, 3,5}, {23,44}}; int t0[] = {1, 2, 3}; // 替换数组元素 Arrays.fill(t0, 9); Arrays.fill(t0, 0, 1, 100); System.out.println(t0[0]); //元组排序 int t4[] = {5,3,0,12,9}; Arrays.sort(t4); Arrays.sort(st3); System.out.println(t4[0]); //会改变原来的数组 System.out.println(st3[0]);//根据字典排顺序排序的 //元组复制 int new1[] = Arrays.copyOf(t4, 3); int new2[] = Arrays.copyOfRange(t4, 2, 9); System.out.println(new1[0]+"?"); System.out.println(new2[0]+"?"); //数组查询 int shuju[] = {33, 2, 44, 1, 0}; Arrays.sort(shuju); // 如果没有进行排序结果是不确定的, 如果有多个指定的元素无法保证找到的是哪一个 int index1 =Arrays.binarySearch(shuju, 2);//若果key在数组中返回搜索的索引值, 否则返回-1或“-"(插入点) int index2 =Arrays.binarySearch(shuju, 2,5, 10); int t2[][] = new int[2][4]; t2[0][0] = 12; for(int i=0; i<t2.length; i++){ for(int j=0; j<t2[i].length; j++){ System.out.print(t2[i][j]); } System.out.println(); } //排序算话 //冒泡算法 int shuzu[] = {12,80,1,14,9,28}; for(int i=1;i<shuzu.length;i++){ for(int j=0;j<shuzu.length-i;j++){ int temp; if(shuzu[j]>shuzu[j+1]) { temp=shuzu[j]; shuzu[j]=shuzu[j+1]; shuzu[j+1]=temp; } } } System.out.println(shuzu[5]); //直接选择排序 for(int i=1;i<shuzu.length;i++){ int index = 0; for(int j=1;j<shuzu.length-i;j++){ if(shuzu[j]>shuzu[index]){ index = j; } int temp = shuzu[shuzu.length-i]; shuzu[shuzu.length-i]=shuzu[index]; shuzu[index]=temp; } } System.out.println(shuzu[5]); //反转排序 for(int j=0;j<(shuzu.length)/2;j++){ int temp; if(shuzu[j]>shuzu[j+1]) { temp=shuzu[j]; shuzu[j]=shuzu[(shuzu.length)/2-1-j]; shuzu[(shuzu.length)/2-1-j]=temp; } } System.out.println(shuzu[5]); } }
版权声明:本文为noperx原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。