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];
}
Now I know the answer myself.
If you don't save it temporarily, it will be overwritten.
545 PHP ssh2_scp_send fails to send files as intended
682 When building Fast API+Uvicorn environment with PyInstaller, console=False results in an error
525 Uncaught (inpromise) Error on Electron: An object could not be cloned
544 rails db:create error: Could not find mysql2-0.5.4 in any of the sources
© 2024 OneMinuteCode. All rights reserved.