I created this insertion sort for a data structures and algorithms about a year ago. I was using visual studio 2008 now i am using 2010. I wanted to use the sort in something else but when I run the code it sorts the highest number as -898583932 or something close to that. Any ideas what might be causing that? Here is my code
#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;
}
                That strangely large negative number probably has something to do with this:
 for (current = 1; current <= last; current++){
     hold = array[current];
You should be more careful with those indices.
You will find the error on this line:
 for (current = 1; current <= last; current++){
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With