Insertion sort algorithm help

This is a discussion on Insertion sort algorithm help within the C Programming forums, part of the General Programming Boards category; I'm supposed to write a program that will use insertion sort to sort 12 numbers in an array. Right now ...

  1. #1
    Registered User
    Join Date
    Oct 2011
    Posts
    7

    Insertion sort algorithm help

    I'm supposed to write a program that will use insertion sort to sort 12 numbers in an array. Right now my program will sort the numbers but always has 12 at the end even if it is not inputted and negative numbers are not working. can anybody help me out?
    Here's what i have so far.
    Code:
    #include <stdio.h>
    
    
    
    
    int main(void)
    {
        int a[12];
        int z = 0, b = 1, j, temp;
    
       while( b <= 12){
       printf("Enter number %d: ", b);
       scanf("%d", &a[z]);
       for(z = 1; z <b; z++)
       {
           temp = a[z];
           j = z - 1;
           while(temp<a[j] && j >=0)
           {
               a[j + 1] = a[j];
               j = j - 1;
           }
           a[j +1] = temp;
       }
    
    
       z++;
       b++;
       }
       for(z = 0; z <=b; z++){
       printf("%d\t", a[z]);
       z++;}
    
    
    
    
    
    
    
    
    
        return 0;
    
    
    
    
    
    
    }

    Thanks!

  2. #2
    Registered User TheBigH's Avatar
    Join Date
    May 2010
    Location
    Melbourne, Australia
    Posts
    426
    If you have an array of 12 elements, the first one is a[0] and the last one is a[11]. You seem to be going from 1 to 12 in places and from 1 to 11 in other places. a[12] does not exist; if you are referring to it, you are referring to memory that doesn't belong to you and anything could happen.
    Code:
    while(!asleep) {
       sheep++;
    }

  3. #3
    Registered User
    Join Date
    Oct 2011
    Posts
    7
    Oh yea that fixed one of my problems but I forgot that its not printing out all the elements of the array only 6 of them. You know whats causing that problem?

  4. #4
    Registered User
    Join Date
    Oct 2011
    Posts
    7
    Never mind I didn't notice i had z incrementing twice i got it working thanks for the help!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Insertion sort
    By UserName112 in forum C++ Programming
    Replies: 2
    Last Post: 10-11-2011, 03:47 AM
  2. Analysis of the Binary Insertion Sort algorithm
    By pc2-brazil in forum C++ Programming
    Replies: 2
    Last Post: 08-01-2011, 10:12 AM
  3. Replies: 1
    Last Post: 01-26-2010, 08:02 AM
  4. Insertion Sort Help
    By Odinwar in forum C++ Programming
    Replies: 8
    Last Post: 12-09-2009, 10:27 AM
  5. Insertion sort... Please help!
    By xMEGANx in forum C++ Programming
    Replies: 11
    Last Post: 11-30-2007, 02:30 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21