简体   繁体   中英

For loop reset (reinitializing i to 1 in specific case) - doesn't work as expected?

I have a predefined function called flip, which changes the order of the elements of a vector like this:

for FLIP(9, [3 2 6 8 5 9 1 7 4], 1, 6) ->
v = [9 5 8 6 2 3 1 7 4] 

void FLIP(int x, int v[100], int w, int y)
{
    int aux;
    for (int p = w; p <= y / 2; p++)
    {
        aux = v[p];
        v[p] = v[y - p + 1];
        v[y - p + 1] = aux;
    }
}

I must use it like this.

I need to make a program which orders the elements of v ascending. I must use this FLIP function and calls with

FLIP(whatever variable I want, whatever array I want, 1, whatever variable I want)

basically, the third argument has to be 1 no matter what.

Well, I thought that I might try to get the highest numbers in their place first, by using two FLIP calls. First should be used to get the highest number in v[1], then to move it to v[n].

Then I should reset the for loop, so I can get the other values in their place, with i=1.

Unfortunately, it doesn't work as expected.

This is my program

#include <iostream>

using namespace std;

void FLIP(int x, int v[100], int w, int y)
{
    int aux;
    for (int p = w; p <= y / 2; p++)
    {
        aux = v[p];
        v[p] = v[y - p + 1];
        v[y - p + 1] = aux;
    }
}

int main()
{
    int n, v[100], max = -32000;
    cin >> n;
    int copie = n;
    for (int t = 1; t <= n; t++)
    {
        cin >> v[t];
    }
    for (int i = 1; i <= n; i++)
    {
        if (v[i] > max)
        {
            max = v[i];
        }
    }
    for (int i = 1; i <= n; i++)
    {
        if (max == 1)
        {
            break;
        }
        if (v[i] == max)
        {
            FLIP(n, v, 1, i);
            FLIP(n, v, 1, n);
            i = 1;
            max--;
            n--;
        }
    }
    for (int i = 1; i <= copie; i++)
    {
        cout << v[i] << " ";
    }
}

But for

 n = 9
v = [3 2 6 8 5 9 1 7 4] 

I get 6 2 3 1 5 4 7 8 9

I really don't understand why that happens. I didn't think this loop would ever end until max becomes 1, and now I can't understand what is happening.

Can you explain to me what I'm doing wrong and how can I fix it? Thanks.

You should use the function only once where the maximum value is the first number, so put up an 'if' to check on that.

Start from i=0 instead of i=1 , because it will jump straight to the second value every time.

for (int i = 1; i <= n; i++)
{
    if (max == 1)
    {
        break;
    }
    if (v[i] == max)
    {
        if (i!=1)
      {
        FLIP(n, v, 1, i);
        FLIP(n, v, 1, n);
      }
        else
        FLIP(n, v, 1, n);

        i = 0;
        max--;
        n--;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM