힙 정렬을 실행하는 프로그램을 작성 중입니다. removeMin 함수를 실행하려고 할 때, 항상 잘못된 결과를 얻고있는 것처럼 보입니다. 잘못된 출력을 제공하는 어레이에서 다운 힐
의 순서로 I 입력 (10) 정수 예를 들어 :3, 6, 8, 3, 89, 35, 7, 9, 1, 4
내가
1, 3, 3, 4, 6, 7, 8, 9, 35, 89
을 기대하지만 얻을 :
: 여기1, 3, 3, 4, 6, 7, 8, 9, 35, 35
내 코드 힙 코드
public class heapsort {
private Integer[] myHeap;
private int size;
private int maxSize;
public heapsort (int x){
myHeap = new Integer[x+1];
maxSize=x;
size=0;
}
public void min(){
if (isEmpty())
System.out.print("Is empty");
else
System.out.println(myHeap[0]);
}
public boolean isEmpty(){
return (size==0);
}
public int size(){
return size;
}
public void insert(int x){
if (size==maxSize)
System.out.println("Heap is full");
else{
size++;
myHeap[size] = x;
upheap(size);
}
}
public void upheap(int x){
int temp;
if (x>1){
if (myHeap[x]<myHeap[x/2]){
temp = myHeap[x];
myHeap[x]=myHeap[x/2];
myHeap[x/2]=temp;
upheap(x/2);
}
}
}
public void removeMin(){
int temp;
temp = myHeap[1];
myHeap[1]=myHeap[size-1];
size--;
if (size>1){
downheap(1);
}
System.out.println(temp);
}
public void downheap(int x){
int temp;
int temp, minIndex, left=2*x, right=2*x+1;
if (right>=size){
if (left>=size)
return;
else
minIndex=left;
}
else{
if (myHeap[left] <= myHeap[right])
minIndex = left;
else
minIndex = right;
}
if (myHeap[x] > myHeap[minIndex]){
temp = myHeap[minIndex];
myHeap[minIndex]=myHeap[x];
myHeap[x]=temp;
downheap(minIndex);
}
}
,
내 메인 프로그램 얹는 :
public static void main (String[] args){
int i=0;
Scanner input = new Scanner(System.in);
System.out.println("Enter array size: ");
int n = input.nextInt();
heapsort myArray = new heapsort(n);
System.out.println("Please input integers");
for (i=1; i<=n; i++){
myArray.insert(input.nextInt());
}
while (!myArray.isEmpty()){
myArray.removeMin();
}
}
}
'removeMin()'에서'if (size> = 1)'만 생각하면됩니까? –
디버거를 사용해 보셨습니까? 또 다른 속임수, 오류를 제공하는 최소한의 예제를 찾으십시오. 세 개의 정수만 사용하여 오류를 재현 할 수 있습니까? 두 개의 정수? 정수 하나? –
removeMin()의'myHeap [1] = myHeap [size-1]; 행은'myHeap [1] = myHeap [size]'여야합니다. 하나의 항목을 삽입하면'insert()'가 끝나면'size'가 1로 설정됩니다. removeMin()을 호출하면 정의되지 않은 값인 myHeap [0]을 반환합니다. –