'Switch positions in array

There are N operations to move an element of the string to the first position. Each move is specified on a line where the index of the item to be moved to the first position is entered. All other elements of the string remain in the same order. For example:

1 2 3 4 5 6 - array
2 1 5 - indexes

The expected results: 6 2 1 3 4 5. I'm not sure how can I use the temp variable to solve this problem. I've tried something like this:

static void MoveFirst(int[] values, int index)        
{
            for (int i = 0; i < values.Length; i++)
            {
                
                if (values[i] == index)
                {
                    int temp = values[i];
                    values[i] = values[i+1];
                    values[i + 1] = temp;
                }
            }

        }


Solution 1:[1]

The text of the problem does not quite match your code and parameters. But if you rely on what you described, you need to shift everything to the left by 1, remembering the element beforehand. You'll get something like this

static void MoveFirst(int[] values, int index)        
{
    int tmp = values[index];
    for (int i = index; i < values.Length; i--)
    {
        values[i] = values[i-1]
    }
    values[0] = tmp;
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 LEGENDA warc