题目:
给定一个未排序的数组x1,x2……xn(n为奇数),请用Java实现一个算法找到该数组的中位数。即:1+(n-1)/2大的数。请不要用Arrays.sort()等java方法。
答案:
public class Test {
public static void main(String[] args) {
// 测试数据,5个元素,数目为奇数,符合要求
int[] a = {77, 9, 15, 56, 2};
// 进行冒泡升序排序
boolean exchange = true;
for (int i = 1; i < a.length && exchange; i++) {
exchange = false;
for (int j = 0; j < a.length - i; j++) {
if (a[j] > a[j + 1]) {
int temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
exchange = true;
}
}
}
// 输出数组的中位数
System.out.println("中位数:" + a[(a.length - 1) / 2]);
}
}
结果:
中位数:15