Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insertion Sort Error

Tags:

c

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;
}
like image 676
shinjuo Avatar asked Nov 08 '11 04:11

shinjuo


2 Answers

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.

like image 121
greatwolf Avatar answered Oct 09 '22 06:10

greatwolf


You will find the error on this line:

 for (current = 1; current <= last; current++){
like image 43
Martin York Avatar answered Oct 09 '22 05:10

Martin York