error404
error404

Reputation: 101

Bugged C Implementation of Straight Insertion sorting

A beginner in C, i'm attempting to implement a Straight Insertion sort. My code has a bug, but i struggle to put my finger on it. If someone experience could point me in the right direction, it'd be much appreciated !!

A few points :

Thanks in advance !

#include <stdio.h>
#include <stdlib.h>


void printTable(int myTable[], int aSize);
void straightInsertion(int myTable[], int mySize);

int main()
{

    int sizeTable = 10;
    int myTable[10] = {100, 90, 80, 70, 60, 50, 40, 30, 20, 10};

    printTable(myTable, sizeTable);
    straightInsertion(myTable, sizeTable);
    printf("\n");
    printTable(myTable, sizeTable);


    return 0;
}

//Loop to display the array
void printTable(int myTable[], int aSize)
{
    int  i = 0;

    for (i = 0; i < aSize; i++)
    {
        printf("%d ", myTable[i]);
    }
}

//Sorting algo
void straightInsertion(int myTable[], int mySize)
{
    int i = 0, j = 0, temp = 0;
    for(j = 1; j<= mySize; j++)
    {
        temp = myTable[j];
        i = j-1;
        while(i>=0 && myTable[i] > temp)
        {
            myTable[i+1] = myTable[i];
            i--;
        }
        myTable[i+1] = temp;
    }
}

Upvotes: 0

Views: 71

Answers (3)

Shreevardhan
Shreevardhan

Reputation: 12641

Refactoring and correcting your straightInsertion function

void straightInsertion(int myTable[], int mySize) {
    int i, j;
    for (i = 1; i < mySize; ++i) {
        int tmp = myTable[i];
        for (j = i; j > 0 && myTable[j - 1] > tmp; j--)
            myTable[j] = myTable[j - 1];
        myTable[j] = tmp;
    }
}

Upvotes: 2

PC Luddite
PC Luddite

Reputation: 6098

In your loop, you used:

for(j = 1; j<= mySize; j++)

Remember that arrays in C are zero-indexed, meaning an array's first index is at 0, not 1, so its last index is going to be mySize - 1. That means that accessing myTable[mySize] is always going to be out of bounds, and accessing that address is undefined behavior.

If you change the line to

for(j = 1; j < mySize; j++)

the code works perfectly.

Upvotes: 1

Jonathan Leffler
Jonathan Leffler

Reputation: 754280

Simple bounds error. You have:

for(j = 1; j<= mySize; j++)

You should be using:

for (j = 1; j < mySize; j++)

to avoid overwriting the end of the array.

Good work on the use of the printing function. May I recommend that you add putchar('\n'); in the function to avoid needing to use printf("\n"); in the calling code.

Upvotes: 2

Related Questions