import javax.swing.JOptionPane;
class heapsort
{
public static int size; //matrix size
public static int heap_size; //heap size
public int left(int i) //look for left child
{
return 2*i;
}
public int right(int i) //look for right child
{
return 2*i+1;
}
//keep the property of heap
public void maxHeapify(int A[],int i) //A matrix; i current node code
{
int l,r,largest;
int temp;
l=left(i);
r=right(i);
if((l<= heap_size)&&( A[l] > A[i]))
largest=l;
else largest=i;
if((r<=heap_size)&&(A[r] > A[largest]))
largest=r;
if( largest!=i)
{
temp=A[i];
A[i]=A[largest];
A[largest]=temp;
}
maxHeapify(A, largest);
}
//build a heap
public void buildHeap(int A[])
{
int i;
heap_size=A.length;
for(i=A.length/2;i>=1;i--)
maxHeapify(A, i);
}
//heapsort algorithm
public void heapSort(int A[])
{
int i,temp;
buildHeap(A);
for(i=A.length/2;i>=2;i--)
{
temp=A[1];
A[1]=A[i];
A[i]=temp;
}
heap_size=heap_size-1;
maxHeapify(A, 1);
}
public static void main(String args[])
{
size= Integer.parseInt( JOptionPane.showInputDialog(null,"请输入数组的大小,size:") );
int seq[]=new int[size];
for(int i=0;i seq[i]=Integer.parseInt( JOptionPane.showInputDialog(null,"请依次输入数组的元素,seq["+i+"]=") );
System.out.print("以下为您输入的数组元素:");
System.out.println("");
for(int i=0;i System.out.print(seq[i]+" ");
heapsort heap=new heapsort();
heap.buildHeap(seq);
heap.heapSort(seq);
}
}
该程序是我做的一个heapsort,编译通过,但是执行时说是数组越界,请指点迷津,谢谢!!!
class TimeTable
{
public static int order; // the orders of 2;
public static int num; // the whole number,num=the ith order of 2;
int table[][]=new int[num][num];
//构造方法,初始化
public TimeTable()
{
int i,j;
for(i=0;i {
for(j=0;j {
table[i][j]=0;
}
}
}
//核心算法
void Table(int k)
{
int n=1;
for(int i=1;i<=k;i++)
n*=2; //n=2^k
for(int i=1;i<=n;i++)
table[1][i]=i; // the elements of 1st row of the table is given
int m=1;
for(int s=1;s<=k;s++)
{
n/=2;
for(int t=1;t<=n;t++)
{
for(int i=m+1;i<=2*m;i++)
{
for(int j=m+1;j<=2*m;i++)
{
table[i][j+(t-1)*m*2]=table[i-m][j+(t-1)*m*2-m];
table[i][j+(t-1)*m*2-m]=table[i-m][j+(t-1)*m*2];
}
}
}
m*=2;
}
}
void display()
{
int i,j;
for(i=1;i {
for(j=1;j {
if(table[i][j]<10)
System.out.print(" "+table[i][j]);
else
System.out.print(" "+table[i][j]);
}
System.out.println("");
}
}
public static void main(String args[])
{
order = Integer.parseInt( JOptionPane.showInputDialog(null,"输入人数,2的k次方 k=\n") );
num=(int)Math.pow(2,order);
num++; //数组默认下标从0开始,因此加大数组
System.out.print("num is "+num+" ");
System.out.print("order is "+order);
System.out.println("");
TimeTable TT=new TimeTable();
TT.Table(order);
TT.display();
}
}
出现的问题同上,还是数组越界!!!
搞不懂是在调用算法函数过程中出现了什么问题!!
本人刚学java,还请指点一二!!