int main ()
{
int *uarr;
uarr = newint [8,3,6,7];
constint size = 4;
int sarr[size];
int z = size-1;
for (int k=size/2;k>0;k--) //Turn the array into a heap.
{
versickern (uarr, k, size);
}
for (int x=0;x<size;x++) //The actual heapsort
{
sarr[z] = uarr[0]; <<-- This is where the error occurs
uarr[0] = uarr[z];
delete [z] uarr;
versickern (uarr, 1, z);
z--;
}
print (uarr, size);
return 0;
}
What is the reason? I don't think you need the function "versickern", that's why I left it out. Tell me if you need it.
Line 6 isn't the way to initialze an array. You must write it like this int uarr = {8,3,6,7}; and you may write constint size = sizeof(uarr) / sizeof(*uarr); (This way it's easier to change the size of the array)
remove line 19. The elment 'z' isn't touched afterwards.
What do you mean by
With" delete [z] uarr;" I wanted to delete the element in position "z" in uarr.
What's supposed to happen when deleted? I mean you print uarr later
I wanted to create the array dynamic, as the program (once the algorithm functions) should accept any user input for an array and then sort it. The dynamic array should just be a test array with preinitialized values so that I don't have to input it everytime I test the program. This is how the finished code should look like:
1 2 3 4 5 6 7
int *arr;
cin >> size;
arr = newint [size];
for (i=0;i<size;i++)
{
cin >> arr[i];
}
Is there a way to create a dynamic array with specific values in it? My heapsort function takes a int*a as argument:
void versickern (int* a, int x, int elements) //Function to turn an array into a heap
{
int temp=0;
while (2*x<=elements && (a[x-1] < a[2*x-1] || a[x-1] < a[2*x]))
{
if (a[2*x-1] > a[2*x])
{
temp = a[2*x-1];
a[2*x-1] = a[x-1];
a[x-1] = temp;
x = 2*x;
}
else
{
temp = a[2*x];
a[2*x] = a[x-1];
a[x-1] = temp;
x=2*x+1;
}
}
}
According to my book, the Heapsort turns an array (uarray in my example) into a heap, then takes the first element which is the largest of them all, and places it in a new array in the correct position (sarr in my example).
It then takes the last element of uarray, puts it in position 0, and turns the entire array into a heap again, but deletes the copied element in the last position. That's why I wanted the delete function.