一道面试题 (朋友给发的):这道题的考点主要是冒泡排序法的应用
给定长度为500的数组,随机放入值为1-50中间的任意整数,请编写程序找出其中的偶数数字,并按照该数字在数组中出现次数从多到少排序输出
package com.julong;
import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.RandomUtils;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
/**
* 测试
* @author julong
* @date 2020/4/26 17:21
* @desc
*/
public class Test {
public static void main(String[] args) {
//保存数据出现的次数
Map<Integer, Integer> maps = new HashMap<Integer, Integer>();
//获取500个数据
int[] arrays = new int[500];
for (int i = 0; i <arrays.length ; i++) {
arrays[i] = RandomUtils.nextInt(0, 51);
}
for (int i = 0; i < arrays.length; i++) {
if(arrays[i] % 2 != 0 || arrays[i] == 0){
continue;
}
if(maps.containsKey(arrays[i])){
int count = maps.get(arrays[i]);
count ++ ;
maps.put(arrays[i],count);
}else{
maps.put(arrays[i],1);
}
}
// System.out.println(JSON.toJSON(arrays));
// System.out.println("获取偶数结果:"+JSON.toJSON(maps));
Object[] keyArray = maps.keySet().toArray();
System.out.println(JSON.toJSON(keyArray));
//冒泡排序法 由小到大
for (int i = 0; i < keyArray.length-1; i++) {
System.out.println("第"+i+"次外循环"+keyArray[i]);
Object temp ;
for (int j = i+1; j < keyArray.length; j++) {
System.out.println("第"+j+"次内循环"+keyArray[j]);
if(Integer.valueOf(keyArray[i]+"") > Integer.valueOf(keyArray[j]+"")){//由小到大
System.out.println("比对结果成功 a>b 进行ab位置调换 ");
temp = keyArray[j];
keyArray[j] = keyArray[i];
keyArray[i] = temp;
System.out.println("第"+i+"次调换结果"+JSON.toJSON(keyArray));
}
}
}
System.out.println("由小到大排序法:"+JSON.toJSON(keyArray));
//冒泡排序法 由大到小
for (int i = 0; i < keyArray.length-1; i++) {
System.out.println("第"+i+"次外循环"+keyArray[i]);
Object temp ;
for (int j = i+1; j < keyArray.length; j++) {
System.out.println("第"+j+"次内循环"+keyArray[j]);
if(Integer.valueOf(keyArray[i]+"") < Integer.valueOf(keyArray[j]+"")){//由大到小
System.out.println("比对结果成功 a<b 进行ab位置调换 ");
temp = keyArray[i];
keyArray[i] = keyArray[j];
keyArray[j] = temp;
System.out.println("第"+i+"次调换结果"+JSON.toJSON(keyArray));
}
}
}
System.out.println("由大到小排序法:"+JSON.toJSON(keyArray));
//冒泡排序法 由大到小
for (int i = 0; i < keyArray.length-1; i++) {
System.out.println("第"+i+"次外循环"+keyArray[i]);
Object temp ;
for (int j = i+1; j < keyArray.length; j++) {
System.out.println("第"+j+"次内循环"+keyArray[j]);
if(maps.get(Integer.valueOf(keyArray[i]+"")) < maps.get(Integer.valueOf(keyArray[j]+""))){//由大到小
System.out.println("比对结果成功 a>b 进行ab位置调换 ");
temp = keyArray[i];
keyArray[i] = keyArray[j];
keyArray[j] = temp;
System.out.println("第"+i+"次调换结果"+JSON.toJSON(keyArray));
}
}
}
System.out.println("由大到小排序法:"+JSON.toJSON(keyArray));
for (int i = 0; i < keyArray.length; i++) {
System.out.print(keyArray[i]);
System.out.println(":"+maps.get(keyArray[i]));
}
}
}