分治算法
分治算法的基本思想是将一个规模为N的问题分解为K个规模较小的子问题,这些子问题相互独立且与原问题性质相同。求出子问题的解,就可得到原问题的解。即一种分目标完成程序算法
算法应用
篮球比赛赛序设计
/**
* 篮球比赛表
* @author Naah
*
*/
public class lanqiubisai {
public static void main(String[] args) {
// TODO Auto-generated method stub
lanqiubisai fenzhi=new lanqiubisai();
int[][] match=fenzhi.getMatch(8);
for (int i = 0; i < match.length; i++) {
for (int j = 0; j < match[i].length; j++) {
System.out.print(match[i][j]+" ");
}
System.out.println();
}
}
/**
* 得到比赛表
* @param teamNum 队伍数量
* @return 比赛表
*/
private int[][] getMatch(int teamNum) {
// TODO Auto-generated method stub
//创建比赛表数组
int[][] match=new int[teamNum][teamNum];
//递归计算比赛表
getMatch(match,teamNum);
return match;
}
/**
* 递归计算比赛表
* @param match 比赛表数组
* @param teamNum 队伍数量
*/
private void getMatch(int[][] match, int teamNum) {
// TODO Auto-generated method stub
//如果队伍数为1
if (teamNum==1) {
match[0][0]=1;
//否则
}else {
//计算当前队伍的一半
int half=teamNum/2;
//计算比赛表左上角
//以一半队伍数作为队伍数量
getMatch(match, half);
//计算比赛表右上角
//行从开始到一半
for (int i = 0; i < half; i++) {
//列从一半到最后
for (int j = half; j <teamNum; j++) {
//右上角比赛的设定为左上角该位置加一半
match[i][j]=match[i][j-half]+half;
}
}
//计算比赛表左下角
//行从一半到最后
for (int i = half; i < teamNum; i++) {
//列从开始到一半
for (int j = 0; j < half; j++) {
//左下角比赛的设定为左上角该位置加一半
match[i][j]=match[i-half][j]+half;
}
}
//计算比赛表右下角
//行从一半到最后
for (int i = half; i < teamNum; i++) {
//列从一半到最后
for (int j = half; j< teamNum; j++) {
//右下角比赛的设定为与左上角相同
match[i][j]=match[i-half][j-half];
}
}
}
}
}