c++ - 使用指针进行选择排序

标签 c++ arrays sorting pointers selection-sort

我正在尝试使用数组指针进行选择排序。

void sort(int size, int *ptr)
{
int temp;
bool swap;
do
{
    swap = false;
    for (int count = 0; count < (size - 1); count++)
    {
        if (*ptr[count] > *ptr[count + 1])
        {
            temp = *ptr[count];
            *ptr[count] = *ptr[count + 1];
            *ptr[count + 1] = temp;
            swap = true;
        }
    }
} while (swap);
}

我收到很多错误说非法方向,因为在使用 * 时它必须是一个指针。我在其他方法中使用它很好,只是这个方法有问题。这是我正在使用的调用。

sort(arraySize, numArray);

一切都在其他方法中声明和工作。

最佳答案

使用 ptr[] 而不是 *ptr[] 因为, ptr 是指针,如果与 [] 一起使用,它会像数组一样返回该位置的元素。

void sort(int size, int *ptr)
{
int temp;
bool swap;
do
{
    swap = false;
    for (int count = 0; count < (size - 1); count++)
    {
        if (ptr[count] > ptr[count + 1])
        {
            temp = ptr[count];
            ptr[count] = ptr[count + 1];
            ptr[count + 1] = temp;
            swap = true;
        }
    }
} while (swap);
}

关于c++ - 使用指针进行选择排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28424462/

相关文章:

c++ - 如何将模板化类实例作为模板参数传递给另一个模板?

c++ - 具有基类的唯一 ptr 的类的复制构造函数

c++ - 在参数化构造函数中将数组作为参数传递

python - 如何按整数对元组的混合列表进行排序?

python - Numpy 的 argsort 是确定性的吗?

sorting - Elasticsearch :尽管fielddata设置为true,文本排序也不起作用

c++ - 如何声明一个函数数组?

c++ - 移植到 MSVS2010 C++ GUI 的 MSVS2010 C++ 控制台代码失败。为什么?

php - 获取一个数组的键,该键位于另一个数组内并包含值

Python 从十六进制字节创建数组