There is a difference between both.
Note: temp will be the considered as the min element of that pass in both code. Because we search for values greater than temp for index i to 0.
Former one:
The inner loop ends either with x = 0 (or) x = i. Here you replace a[x] with temp. So obviously the temp(min value of that pass) will be inserted correctly in its appropriate place.
+----------------+
Initial Array | 4 3 2 1 6 |
+----------------+
+-------------------+ | +-------------------+
| i = 1 | temp = 3 | | i = 2 | temp = 2
+-------+-----------+ | +-------+-----------+
| x = 1 | 4 4 2 1 6 | arr[1] = 4 | | x = 2 | 3 4 4 1 6 | arr[2] = 4
+-------+-----------+ | +-------+-----------+
| 3 4 2 1 6 | arr[0] = temp | | x = 1 | 3 3 4 1 6 | arr[1] = 3
+-------------------+ | +-------+-----------+
| | 2 3 4 1 6 | arr[0] = temp
| +-------------------+
+-------------------+ | +-------------------+
| i = 3 | temp = 1 | | i = 4 | temp = 6
+-------+-----------+ | +-------------------+
| x = 3 | 2 3 4 4 6 | arr[3] = 4 | | 1 2 3 4 6 | arr[4] = temp
+-------+-----------+ | +-------------------+
| x = 2 | 2 3 3 4 6 | arr[2] = 3 |
+-------+-----------+ |
| x = 1 | 2 2 3 4 6 | arr[1] = 2 |
+-------+-----------+ |
| 1 2 3 4 6 | arr[0] = temp |
+-------------------+ |
Latter one:
Here,
if arr[x-1] > temp do arr[x] = arr[x-1]
else do arr[x] = temp
So no proper insertion is done and values are lost.
+----------------+
Initial Array | 4 3 2 1 6 |
+----------------+
+-------------------+ | +-------------------+
| i = 1 | temp = 3 | | i = 2 | temp = 2
+-------+-----------+ | +-------+-----------+
| x = 1 | 4 4 2 1 6 | arr[1] = 4 | | x = 2 | 4 4 4 1 6 | arr[2] = 4
+-------+-----------+ | +-------+-----------+
| 4 4 2 1 6 | | | x = 1 | 4 4 4 1 6 | arr[1] = 4
+-------------------+ | +-------+-----------+
| | 4 4 4 1 6 |
| +-------------------+
+-------------------+ | +-------------------+
| i = 3 | temp = 1 | | i = 4 | temp = 6
+-------+-----------+ | +-------------------+
| x = 3 | 4 4 4 4 6 | arr[3] = 4 | | 4 4 4 4 6 | arr[4] = temp
+-------+-----------+ | +-------------------+
| x = 2 | 4 4 4 4 6 | arr[2] = 4 |
+-------+-----------+ |
| x = 1 | 4 4 4 4 6 | arr[1] = 4 |
+-------+-----------+ |
| 4 4 4 4 6 | |
+-------------------+ |
Instead of using break, you can control the code with for-loop itself.
#include <stdio.h>
int main()
{
int i,x,temp,arr[5]={5,6,5,1,2};
for(i=1;i<5;i++)
{
temp=arr[i];
for(x=i;arr[x-1]>temp;x--)
arr[x]=arr[x-1];
arr[x]=temp;
}
for(i=0;i<5;i++)
printf("\t%d",arr[i]);
return 0;
}