Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

[Solved]How do I use the insert method of sorting tables?

Asked by 5 years ago
Edited 5 years ago

I have been taking a class on computer science on khan academy and have run into a really confusing problem. Here is an excerpt from the lesson:

Fix the insert function to correctly insert the given value into the array.

The insert function takes three parameters as inputs: array, rightIndex, and value.

Before the insert function is called: * the elements from array[0] to array[rightIndex] are sorted in ascending order.

After calling the insert function: * value and the elements that were previously in array[0] to array[rightIndex], should be sorted in ascending order and stored in the elements from array[0] to array[rightIndex+1].

In order to do this, the insert function will need to make room for value by moving items that are greater than value to the right. It should start at rightIndex, and stop when it finds an item that is less than or equal to value, or when it reaches the beginning of the array. Once the function has made room for value, it can write value to the array.

I am struggling to understand how to do this. Please tell me if I am going about this the wrong way. Here is my code:

local array = {3, 4, 2, 11, 13, 2, 9, 6}

local function insert(tbl, startingPoint, num)

    for i = 1, (startingPoint + 1) do

        local var = tbl[i]

        for j = i, 1, -1 do

            if j > 1 then
                if var < tbl[j - 1] then

                    tbl[j] = tbl[j - 1]
                    tbl[j - 1] = var

                else

                    tbl[j] = var     -- here is where I think the problem is 

                end

            else

                tbl[j] = var

            end
        end
    end
end

insert(array, 5, 2)

my problem is that else statement on line 17. It makes it so that when I call the function the output when I print the table as a string is: {2, 13, 13, 13, 13, 13, 9, 6} if I could have any help I would really appreciate it.

here is a link to the lesson problem. here is the link to the concept explanation. I would really appreciate it if someone could help me understand how to do this. Thanks!

Answer this question