while循环没弄好(没起作用),应该用while(people.length>=1)代替while(counter!=M),退出循环后再输出people[0];不过不再实现了。
实现一个基于环形链表数据结构的环形队列来做会更好一些。
package Algorithm;
import edu.princeton.cs.algs4.*;
public class Josephus {
public static void main(String[] args){
//完成准备工作
int N=StdIn.readInt();
int M=StdIn.readInt();
int[] people=new int[N];
for(int i=0;i<N;i++)
people[i]=i;
//从数组的第一个元素往后面依次计数直至计数器的值等于M,取出当前数组索引对应的元素,
//如果到达数组最末,返回数组头继续计数。每次取出元素后数组长度缩小一位。
//index指向数组索引,counter表明报(计)数器
int index=0,counter=1;
while(counter!=M){
counter++;
if(index==people.length-1)
index=0;
else
index++;
if(counter==M){
//找到人以后,将people数组内该索引处的元素清除,数组长度减一
StdOut.println(people[index]);
int[] alive =new int[people.length-1];
for(int n=0;n<people.length-1;n++){
if(n<index)
alive[n]=people[n];
else
alive[n]=people[n+1];
}
if(people.length==1)
break;
people=alive;
//index处的元素撤去,此时counter、index均指向这个"死"元素,在下一次循环中counter、index要加1,故此处如此处理
counter=0;
index--;
}
}
}
}