使用指针进行选择排序
Using a pointer for 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);
}
错误在*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);
}
相关文章:
- C++选择排序算法中的逻辑错误
- 高级选择排序 - 在一次迭代中搜索两个元素
- 选择排序C++(已修改)并非适用于所有情况
- C++为什么我的指针选择排序中存在分段错误?
- 为什么这个选择排序算法仍然切换一个元素,当它已经是其他元素中最小的元素时?
- 选择排序时交换函数调用的数量和完成的交换次数是否相同?
- 如何使用cpp编写选择排序算法以降序对元素列表进行排序?
- 使用选择排序对数组数据结构进行排序,但它不起作用
- c++ 选择排序在特定情况下不起作用
- 修改的选择排序,选择最大的数字,然后交换到最后
- 如何选择排序一些结构
- 选择排序以查找未排序数组中的最大数字
- 我的选择排序代码是否存在导致它跳过数组中的元素的问题?
- 给定数组范围的选择排序问题
- 选择排序算法生成无序结果
- 使用C 中的一系列字符串的选择排序
- 从递归向后选择排序函数调用 max 和交换函数
- 为 STL 列表编写选择排序
- 跟踪选择排序中的交换和比较次数
- 字母选择排序程序的问题