C++ does not understand the role of temporary variables when implementing insertion sorting

Asked 2 years ago, Updated 2 years ago, 42 views

I'm learning about insertion sorting, and I have one question, why should I use the variable temp?

Insert Sort|Programming Place Plus Algorithms and Data Structure Edition

Correct behavior code:

interry[]={5,2,8,3,1};

    for (inti=1; i<5;i++)
    {
    int temp = arry [i];
        int j = i-1;
        while((j>=0) and (arry[j]>temp))
        {
            arry[j+1] = arry[j];
            j = j-1;
        }
        arry[j+1] = temp;
    }

    for (inti=0; i<5;i++)
    {
        cout<arry[i];
    }

If you try to access the array using the while conditional statement without using the temp variable as shown below, you cannot verify the correct behavior.
Please let me know.

Code without temp:

 for (inti=1;i<5;i++)
    {
      // int temp = arry [i];
        int j = i-1;
        while((j>=0) and (arry[j]>arry[i]))
        {
            arry[j+1] = arry[j];
            j = j-1;
        }
        arry[j+1] = arry[i];
    }

c++ algorithm

2022-09-30 17:57

1 Answers

Now I know the answer myself.

If you don't save it temporarily, it will be overwritten.


2022-09-30 17:57

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.