众数问题算法有很多实现,众数问题的实现选择要考虑多个方面,这里用到了快速排序算法思想,将每次递归计数到返回值Map里,再与之比较
public class ModeAlgorithmT {
private int[] arrTemp;
public ModeAlgorithmT(int[] arr) {
// TODO Auto-generated constructor stub
this.arrTemp = arr;
Map<Integer, Integer> xx = quickSort(arrTemp, 0, arr.length - 1);
Iterator it = xx.keySet().iterator();
int key, count = 0, mode = 0;
while (it.hasNext()) {
key = Integer.parseInt(it.next().toString());
if (xx.get(key) > count) {
mode = key;
count = xx.get(key);
}
System.out.println(xx.size());
}
System.out.println("众数是" + mode);
System.out.println("重数是" + count);
}
public Map<Integer, Integer> quickSort(int[] arr, int lowIndex,
int highIndex) {
int low = lowIndex;
int high = highIndex;
Map<Integer, Integer> xx = new HashMap<Integer, Integer>();
int mid = 0, count = 0;
if (highIndex > lowIndex) {
mid = arr[lowIndex + (highIndex - lowIndex) / 2];
while (low <= high) {
while ((low < highIndex) && (arr[low] < mid)) {
++low;
}
while ((high > lowIndex) && (arr[high] > mid)) {
--high;
}
if (low <= high) {
int temp = arr[low];
arr[low] = arr[high];
arr[high] = temp;
++low;
--high;
}
if (high != low) { //避免重复计数
if (arr[high] == mid) {
count++;
}
if (arr[low] == mid) {
count++;
}
} else {
if (arr[high] == mid) {
count++;
}
}
}
if (lowIndex < high) {
Map<Integer, Integer> temp = quickSort(arr, lowIndex, high);
int key = temp.keySet().iterator().next();
if (temp.get(key) > count) {
count = temp.get(key);
mid = key;
}
}
if (low < highIndex) {
Map<Integer, Integer> temp = quickSort(arr, low, highIndex);
int key = temp.keySet().iterator().next();
if (temp.get(key) > count) { //比较递归调用返回的重数与众数
count = temp.get(key);
mid = key;
}
}
}
xx.put(mid, count); //存入当前众数与重数
return xx;
}
}