1、冒泡排序
package com.xuyilong;
import java.util.Arrays;
public class Sort {
public static void main(String[] args) { int[] a={9,8,7,6,5,4,3,2,1}; bulbleSort(a); System.out.println("结果为:"+Arrays.toString(a)); } public static void bulbleSort(int[] a){ int temp=0; System.out.println(Arrays.toString(a)); for (int i = 0; i < a.length; i++) { System.out.println("第"+(i+1)+"轮"); for (int j =0; j < a.length-1-i; j++) { System.out.println("\t"+"第"+(j+1)+"次"); if (a[j]>a[j+1]) { temp=a[j]; a[j]=a[j+1]; a[j+1]=temp; } System.out.println(Arrays.toString(a)); } } } }
|
2、随机生成50个数字(整数),每个数字的范围是[10,50],统计每个数字出现的次数以及出现次数最多的数字与他的个数,最后将每个数字及其出现的次数打印出来,如果某个数字出现次数为0,则不要打印它,打印时按照数字的升序排列。
package com.xuyilong;
import java.util.Arrays; import java.util.Map; import java.util.TreeMap;
public class CountNum { public static void main(String[] args) { int[] a = new int[50]; for (int i = 0; i < a.length; i++) { a[i] = (int) (Math.round((Math.random() * 40)) + 10); } System.out.println(Arrays.toString(a)); Map<Integer, Integer> m = new TreeMap<>(); for (int i = 0; i < a.length; i++) { if (!m.containsKey(a[i])) { m.put(a[i], 1); } else { m.put(a[i], m.get(a[i]) + 1); } } int maxK = 0; String str = ""; for (Map.Entry<Integer, Integer> e : m.entrySet()) { System.out.println("数字" + e.getKey() + "出现了" + e.getValue() + "次"); if (e.getValue() == maxK) { str = str + e.getKey() + ", "; } else if (e.getValue() > maxK) { maxK = e.getValue(); str = e.getKey().toString() + ", "; } } System.out.println("出现最多次数的数字是:" + str + "次数为" + maxK + "次"); } }
|