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.
© 2024 OneMinuteCode. All rights reserved.