0

I wrote 2 functions-for insertion sort and selection sort. The logic for selection sort is wrong but still, I'm getting the correct output. I get the wrong output if I comment on the insertion_sort() call. Why is my original value array changing after insertion sort even when I used "call by value"?

The output is 2 3 4 5 6 2 3 4 5 6

If I comment insertion sort call, I get 2 2 2 2 2 which is the o/p I should actually get.

#include<stdio.h>
void  insertion_sort(int [], int);
void selection_sort(int [], int);
int main()
{
    int array[5] = {6, 5, 4, 3, 2};
    int n = 5;
    insertion_sort(array, n);
    selection_sort(array,n);
}
void insertion_sort(int arr[5], int n)
{
    int i, j, key;
    for (i=1; i < n; i ++)
    {
        key = arr[i];
        j = i - 1;
        while (j >=0 && arr[j]>key)
        {
            arr[j + 1] = arr[j];
            j = j - 1;
        }
        arr[j + 1] = key;
    }
    for (i = 0; i < n; i ++)
    {
        printf("%d ", arr[i]);
    }
}
void selection_sort(int arr[5], int n)
{
    int i, j, temp;
    for (i=0;i<n-1;i++)
    {
        int min_index = i;
        for(j=i+1;j<n;j++)
        {
            if(arr[j]<arr[i])
            {
                arr[i] = arr[j];
            }
        }
    }
    for(i=0;i<n;i++)
    {
        printf("%d ", arr[i]);
    }
}
ChrisMM
  • 8,448
  • 13
  • 29
  • 48
  • Arrays are never passed by value. The array decays to a pointer to its first element. – Retired Ninja May 17 '22 at 18:43
  • 1
    When you pass an array to a function, you're actually passing a pointer. The pointer itself is by value, but it's still pointing to the same data that the original array was pointing to, thus changing the array's contents inside the function will affect the array outside the function. – ChrisMM May 17 '22 at 18:44

0 Answers0