0

Here I am implementing a simple sort (insertion), but I'm not getting the correct size of the array. Namely, my length variable is getting set equal to 1. Also, what ways could I optimize my code for this insertion sort algorithm? Thanks

void insertionSort(int a[])
{
    int sorted = 1;
    int length = sizeof(a) / sizeof(int);
    int i = 0;
    int tmp;

    printf("%d   ", length);

    if (length < 2)
        return;

    for (i = 1; i < length - 1; i++)
    {
        sorted = i;
        while (a[sorted] < a[sorted - 1] && sorted > 0)
        {
            tmp = a[sorted];
            a[sorted] = a[sorted - 1];
            a[sorted - 1] = tmp;
            sorted--;
        }
    }
}
Kara
  • 6,115
  • 16
  • 50
  • 57
slinhart
  • 562
  • 5
  • 17

2 Answers2

0
int length = sizeof(a) / sizeof(int);

This returns the size of a pointer a, divided by the size of an int. Always equal to one.

You will have to pass length to the function, void insertionSort(int a[], size_t length){

The function that creates the array has to keep track of the number of elements that are active in the array in order to do this.

jim mcnamara
  • 16,005
  • 2
  • 34
  • 51
  • Not necessarily 1: if this is a 64-bit compilation on Unix, the size of the pointer will usually be 8 and the size of the integer will be 4 so the answer will be 2. It won't often be the size of the array, though. – Jonathan Leffler Dec 15 '13 at 06:56
0

C arrays doesn't really exists. This essentially means that you don't have good abstract support for arrays in C. As an example of this, if I give you (you are the function insertionSort) an array (say a) you won't be able to determine it size! Arrays have no size in C.

So what is sizeof(a)? First a is not an array but a constant pointer to the memory address of the first element; that's all. Then sizeof(a) just gives you the size of the pointer a.

If you want to manage arrays in C, you must use a variable to store its length. This is why most of functions that deals with arrays have additional parameters length.

Jean-Baptiste Yunès
  • 34,548
  • 4
  • 48
  • 69