Nguyễn Quốc Khánh - 1 year ago 82

C Question

My code works properly when all variables and array are defined as int, but if I change the type to unsigned int, it won't work.

Here is my code:

`#include <stdio.h>`

#include <stdlib.h>

void swap(unsigned int *a, unsigned int *b){

unsigned int temp;

temp=*a ; *a=*b ; *b=temp;

}

void heapify(unsigned int A[], unsigned int i, unsigned int n){

//sort from root i

unsigned int L = 2*i+1;

// node left child

unsigned int R = 2*i+2;

//node right child

unsigned int max = i;

//set max node is root

if(L < n && A[L] > A[max]) max = L;

//if node child > max, set that node is max

if(R < n && A[R] > A[max]) max = R;

if(max != i) {

swap(&A[i], &A[max]);

heapify(A, max, n);//recursive tree with root is node swaped

}

}

void buildHeap(unsigned int A[], unsigned int n){

unsigned int i = n/2 - 1;

for(; i >= 0; i--) heapify(A, i, n);

}

void heapSort(unsigned int A[], unsigned int n){

buildHeap(A, n);

unsigned int i = n-1;

for(; i >= 0; i--){

swap(&A[0], &A[i]);

heapify(A, 0, i);

}

}

void PrintArray(unsigned int A[], unsigned int n){

unsigned int i;

for(i = 0; i < n; i++){

printf("%d ", A[i]);

}

}

int main(){

unsigned int A[]={1,6,8,9,7,1,65,92,2,9,2,5,73,9,1,5};

unsigned int n=sizeof (A)/sizeof(unsigned int);

PrintArray(A,n);

heapSort(A,n);

PrintArray(A,n);

}

The output is stuck at print the old array and nothing happens after that.

What should I do?

Answer Source

The problem is at `buildHeap`

- you set your iterator as `unsigned int`

, and run a loop until `i`

is no longer positive - which in the cash of `unsigned int`

will never happen.

```
void buildHeap(unsigned int A[], unsigned int n){
unsigned int i = n/2 - 1;
for(; i >= 0; i--) heapify(A, i, n);
}
```