1. ## Simple array sort.

Hi!

I've got to sort an array by moving the elements. Program is getting elements one by one and sort it on board.

Example:

Input:

2
4
6
3
7
1
4
2

Output:

1: [ 2 ]
2: [ 2 4 ]
3: [ 2 4 6 ]
4: [ 2 3 4 6 ]
5: [ 2 3 4 6 7 ]
6: [ 1 2 3 4 6 7 ]
7: [ 1 2 3 4 4 6 7 ]
8: [ 1 2 2 3 4 4 6 7 ]

This is my program, but it has many bugs esspecially with the loops. I don't know how to fix it. Thanks for all you help.

Code:
```#include<stdio.h>

int main()
{
int tab[100],i , x, poz, ile=1;

while(scanf("%d",x))
{

poz=0;

while(tab[poz]<x && poz<ile)

{

++poz;

}

for(i=ile;i<=poz;i--)
tab[i]=tab[i-1];

tab[poz]=x;

ile++;

printf("[");

for(i=0;i<=poz;++i)
printf(" %d ",tab[i]);

printf("]\n");

}

}```

2. scanf() needs an address for n, so it can modify it.

Add a & just before the x.

int main() needs a return 0 at the end of it.

A few other dodgy bits of code, but I haven't studied them through yet.

This appears ok, but is hugely untested. The array tab[] must be set to all zero's before this algorithm begins to work, imo.

Code:
```#include<stdio.h>

int main()
{
int i, x, poz, ile=1;
int tab[100] = { 0 };

while(scanf("%d", &x))
{
if(x < 0) break;
poz=0;

while(tab[poz] < x && tab[poz])
{
++poz;
}

for(i=ile-2; i>=poz; i--) {
tab[i+1]=tab[i];
tab[i] = 0;
if(i == 0) break;
}
tab[poz]=x;
printf("[");
for(i=0;i<ile;++i)
printf(" %d ",tab[i]);

printf("]\n");
ile++;
}

return 0;
}```

3. Thank you very much!

It' almost perfect, but it's one problem - with 0.

It doesn't sort array properly, when it loads zero...

4. The other day I went to my doctor - I complained that it hurt when I did this.

He said "then don't do that".

I'll look at it in a bit. You do the same.

5. Originally Posted by milky
It doesn't sort array properly, when it loads zero...
because of
Code:
`while(tab[poz] < x && tab[poz])`
0 will be the smallest number going by your non-negative number approach.After inserting 0 at it right place the algorithm fails to find poz because tab[poz] = 0 and while condition evaluates to false and hence it fails.

The algorithm you are implementing is Insertion Sort

EDIT:It still has a bug.Try entering zero first
The condition should have been
Code:
```        while( tab[poz] < x &&  (poz < ile - 1) )
{
++poz;
}```

6. Oh! I figured it out:

corretly:

Code:
`while(tab[poz] < x && poz<(ile-1))`
Thank for your help, i do appreciate it

And i've got last question. How to change this program, that it make insertion sort?

Like:

Input:

2
3
4
5
6
0

Output:

6
5
4
3
2
0

What should i change?