我试图在java中实现一个算法,它接受1到100之间的整数数组并将它们打印成直方图。我相信我已经为此推断了一个线性解决方案,但不知道它是O(n)还是O(10n)等。我已经将算法基于计数排序,因为我理解它是最有效的数组排序算法。是否有更有效的方法在将数组显示为直方图的情况下对数组进行排序而不是操作计数排序?
到目前为止的方法:
public static void histogram(int[] array){
for(int i = 0; i< array.length; i++){
array[i] = (array[i] - 1)/10;
}
//create quantity array of size 10 and fill with 0
int[] quantity = new int[10];
for(int i = 0; i <= 9; i++){
quantity[i] = 0;
}
//increment value of quantity index = array[i]
for(int i = 0; i< array.length; i++){
quantity[array[i]]++;
}
//set values of number group column in histogram
int low = 1;
int high = 10;
//string to pad the rows with shorter group names (1-10)
String pad = " ";
//start building histogram
StringBuilder his = new StringBuilder(
"______________________________________________ \n"); //ceiling
//loop 10 times (number of groups = 10)
for(int i = 0; i<= 9; i++){
his.append(low + " - " + high + pad + " | "); //number group column
//append asterisks equal to value stored in quantity[i]
for(int j = 0; j < quantity[i]; j++){
his.append("*");
}
his.append("\n"); //move to next line
//set values of next number group
low += 10;
high += 10;
//pad for 11-20 ... 81-90
pad = " ";
if (high == 100){
pad = ""; //pad for 91-100
}
}
his.append("______________________________________________"); //floor
System.out.print(his); //print entire historgram
}
以下是输出示例:
1 - 10 | **********
11 - 20 | **********
21 - 30 | *********
31 - 40 | *******
41 - 50 | ***********
51 - 60 | ***********
61 - 70 | **********
71 - 80 | **********
81 - 90 | ************
91 - 100 | **********
对于大小的阵列,我需要花费100个时间来执行算法:473397ns
(stackoverflow似乎弄乱了格式,但所有内容都打印出来)