No, key equals the value contained in the element located at height[j]. First time through, that element is actually height[2], 2nd time through it's height[3] etc.
As for i, yes, the first time through the loop i = 1, second time i = 2, etc.
for(int j=2;j<10;j++)
{
int key = heights[j]; //so key is 2? (no, 2 is the starting index of the for loop... what this means is you have an array with the sort starting at heights[2] and going untill heights [9] (less then 10))
int i = j-1;//i is 1? // yes, initally it is one, but as the loop progresses it will i will count from 1 to 8, always being one less then j
while(i>0 && heights[i] > key)
{
heights[i+1]=heights[i];
i=i-1;
}
heights[i+1] = key;
}
I tried to understand the while loop part but i had difficulties... This appears to be something called a Bubble sort, or similar (if i am not mistaken, Im still new too)... Here is what i think is a similar but easier algorithm...
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
int heights[50];
//init heights to something random
bool swapped;
do {
swapped = false;
for (int i = 0; i <49; i++)
{
if (heights[i] < heights [i + 1])
{
swapped = true;
int temp = heights[i+1]; // temporary holder for variables during the swap, some algorithms dont need this but its easier to explain
heights [i+1] = heights [i];
heights[i] = temp;
}
}while (swapped == true); // if no changes are made, the array is sorted and thus we are done
This should work, it is bubblesort which is simple but slow... computation speed increases exponentially with the size of the data (assuming it is not already in order, if it is its fast)
that's the psuedocode that I used to create my code? and this was the brief
Implement the following pseudocode using your designated language. In particular, observe that this is a procedure taking an array as input (you must also pass the length of the array as a parameter for C++). Remember the things to watch for - such as the difference in indexing between pseudocode and real code!
have I done it correctly then ? I still don't understand what the pseudo code is meant to do it says it takes an array as an input??