Insertion Sort

Well, I was trying to do some sorting with random integer values in an array and thankfully I have made it to work.

The problem now is in this pic:
http://oi49.tinypic.com/2dlosqu.jpg

I'm a hell of confused as to when variable i became 10 , it still compared value 19 to value 96 which is var[8] and var[7] instead of var[10] and var[9].

This is my code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <iostream>
#include <time.h>
#include <cstdlib>
using namespace std;

int main()
{
    srand (time(NULL));
    int var[10];
    for (int i=0;i<10;cout<<var[i++]<<" ")
        var[i]=rand()%100;
    cout<<endl;
    for (int i=9;i>0;i--){
        while (var[i]<var[i-1] &&  cout<<"comparing "<<var[i]<<" to "<<var[i-1]<<endl)
        {
            swap(var[i],var[i-1]);
            cout<<"Value "<<var[i]<<" switched to "<<var[i-1]<<endl;
            cout<<"i was "<<i<<" after the switch . ";
            i++;
            cout<<"i is now "<<i<<endl<<endl;
        }

    }
        cout<<endl;
    for (int i=0;i<10;i++)
        cout<<var[i]<<" ";




    return 0;
}


Cheers!
var[10]
That would be accessing outside array bounds. Will lead to unexpected behavior.
Topic archived. No new replies allowed.