Insertion Sort

I created an insertion sort for an assignment about a year ago for a data structures and algorithms class and now when I run it the highest number in the sort comes out as a -898549384 or something like that. It didnt used to do that so I thought. I am now using visual studio 2010 could that be it? Here is the 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
33
34
35
36
37
38
39
40
41
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

void insertionSort(int array[], int last){
     int hold;
     int walker;
     int current;

     for (current = 1; current <= last; current++){
         hold = array[current];
         for (walker = current - 1; 
             walker >= 0 && hold < array[walker]; walker--){
                    array[walker + 1] = array[walker];
             }
          array[walker + 1] = hold;
     }
     return;
}

int main(int argc, char *argv[])
{
  int numbers[10];
  int i;
  
  srand(time(NULL));
  for (i = 0; i < 10; i++){
      numbers[i] = rand() % 100;
  }
  printf("Unsorted Numbers\n-------- -------\n");
  for (i = 0; i < 10; i++){
      printf("%d,", numbers[i]);
  }
  insertionSort(numbers, 10);
  printf("\nSorted Numbers\n-------- -------\n");
  for (i = 0; i < 10; i++){
      printf("%d,", numbers[i]);
  }
  system("PAUSE");	
  return 0;
}
Last edited on
1
2
for (current = 1; current <= last; current++){
         hold = array[current];

Here, when current == last you will have overstepped the bounds of the array by one. You probably meant to do current < last.

It didnt used to do that so I thought.

It probably didn't. Overstepping array bounds produces undefined behaviour. In general, undefined behaviour presents itself like this. The program may run fine at one time but could crash the next.
thank you very much
Topic archived. No new replies allowed.