Trying to implement HeapSort
I am getting stuck on heapSort. I have some code but I think its pretty wrong since I'm having hard time compiling it. Any suggestions? Heap sort should be fairly easy to implement but I have bunch of syntax errors. Here's my code:
/* Framework for Heap Sort
* CS333 Spring 2011
*
*/
#include <stdio.h>
#define MAX_SIZE 1000000
int data[MAX_SIZE];
int n;
int j;
int parent(int j) {
if(j==1)
return 0;
if(j%2==0)
return ( (j / 2)-1);
else
return ( (j / 2));
}
int left(int j) {
return (2 * j) + 1;
}
int right(int j) {
return (2 * j) + 2;
}
void heapify(int data[], int j) {
int l = left(j), great;
int r = right(j);
if ( (data[l] > data[j]) &&开发者_如何学Go (l < sizeof(data))) {
great = l;
}
else {
great = j;
}
if ( (data[r] > data[great]) && (r < sizeof(data))) {
great = r;
}
if (great != j) {
int temp = data[j];
data[j] = data[great];
data[great] = temp;
heapify(data, great);
}
}
int BuildMaxHeap(int data[]) {
for (int j = (sizeof(data) - 1) / 2; j >= 0; j--) {
heapify(data, j);
return data;
}
}
void HeapSort(int data[]) {
BuildMaxHeap(data);
for (int j = sizeof(data); j > 0; j--) {
int temp = data[0];
data[0] = data[data.sizeof() - 1];
data[sizeof(data) - 1] = temp;
sizeof(data) = sizeof(data) - 1;
heapify(data, 0);
}
}
int main()
{
int i;
/* Read in the data */
n = 0;
while (scanf("%d", &data[n]) == 1)
++n;
/* Sort the numbers low to high */
HeapSort(data);
/* Print out the data */
for (i = 0; i < n; ++i)
printf("%d", data[i]);
}
Most of your problems seem to be in your HeapSort routine:
void HeapSort(int data[]) {
BuildMaxHeap(data);
for (int j = sizeof(data); j > 0; j--) {
When you pass an array to a function like this, what the function receives is actually a pointer. Using sizeof
on that pointer will not tell you about the size of the data pointed to by the pointer -- it'll just tell you how many bytes the pointer itself occupies (typically 4). You probably want to pass the array size as a parameter:
void HeapSort(int *data, size_t data_size) {
and throughout the rest of the routine, you'll refer to data_size
, not sizeof(data)
.
int temp = data[0];
data[0] = data[data.sizeof() - 1];
data[sizeof(data) - 1] = temp;
sizeof(data) = sizeof(data) - 1;
sizeof(whatever)
is also essentially a constant, not a variable; you can't use it as the target of an assignment (but, again, using data_size
as suggested above will let you do the assignment).
精彩评论