[英]c++ swapping content of array - Selection Sort
I'm new to C++.我是 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:在 main 中,数组定义为:
int *sel_nums = new int[n];
And I'm calling selection sort in main:我在 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?有没有人对为什么这种情况不断发生有任何意见?
You allocated dynamically an array of objects of the type int
.您动态分配了一个
int
类型的对象数组。
int *sel_nums = new int[n];
This array you are going to pass to the function selection_sort
.您将要传递给函数
selection_sort
这个数组。 So the function declaration will look at ;east like所以函数声明将看起来像 ;east
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或者你可以使用标准的 C++ 函数
std::swap
像
#include <utility>
//...
if ( min_ind != i )
{
std::swap( m[i], m[min_ind] );
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.