c++sortingdynamic-memory-allocationselection-sortfunction-declaration

c++ swapping content of array - Selection Sort


I'm new to C++. I was attempting to write a function for selection sort the following way.

void selection_sort(int* m[], int array_size) {
    for (int i = 0; i < array_size; i++) 
      int min_ind = i;
      for (int j = i+1; j < array_size; j++){
        if (m[min_ind] > m[j]){
            min_ind = j;
        }
      }
      int temp = *m[i];
      *m[i] = *m[min_ind];
      *m[min_ind] = temp;
    }
  }

Within main, the array is defined as:

int *sel_nums = new int[n];

And I'm calling selection sort in main:

selection_sort( &sel_nums, x );

I keep getting an error that says:

Segmentation fault (core dumped)

Does anyone have any input on why this keeps happening?


Solution

  • You allocated dynamically an array of objects of the type int.

    int *sel_nums = new int[n];
    

    This array you are going to pass to the function selection_sort. So the function declaration will look at ;east like

    void selection_sort( int m[], int array_size ); 
    

    The compiler implicitly adjust the parameter having the array type to pointer to the array element type. That is the above declaration is equivalent to

    void selection_sort( int *m, int array_size ); 
    

    So the function can be called like

    selection_sort( sel_nums, n );
    

    To swap two elements of the array within the function you can write

      if ( min_ind != i )
      {
          int temp = m[i];
          m[i] = m[min_ind];
          m[min_ind] = temp;
      }
    

    Or you could use the standard C++ function std::swap like

    #include <utility>
    
    //...
    
    if ( min_ind != i )
    {
        std::swap( m[i], m[min_ind] );
    }