使用指针进行选择排序

Using a pointer for selection sort

本文关键字:选择 排序 行选 指针      更新时间:2023-10-16

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

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);
}

错误在*ptr[count]中这是指针取消引用的错误语法。

执行ptr[count]*(ptr + count)

以下是已删除编译错误的版本。

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++为选择排序函数使用指针

更多示例:http://www.codemiles.com/c-examples/c-selection-sort-t2916.html

*ptr[count]没有任何意义

ptr-指针*ptr-值-取消引用

这是正确的结构在使用数组的指针表示法时不能使用*,使用不带"*"的指针名称是指指针数组的0索引

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);
}