C++中基于指针的冒泡排序
Pointer Based Bubble Sort in C++
我一直在尝试使用C++中基于指针的气泡排序来获得对用户输入的数组进行排序的代码。代码编译时没有出现错误,但数组没有得到排序。指针从来都不是我的强项,我无法让它们正确工作。这是我的密码。
#include <iostream>
using namespace std;
int main()
{
int arr[10];
int i = 0;
for (i = 0; i < 10; i++)
{
cout << "Enter a number: ";
cin >> arr[i];
}
int *ptr = &i;
for (int j = 0; j < 9; j++)
{
if (*(ptr + j) > *(ptr + j + 1))
{
int temp = *(ptr + j);
*(ptr + j) = *(ptr + j + 1);
*(ptr + j + 1) = temp;
}
}
cout << endl;
for (i = 0; i < 10; i++)
cout << arr[i] << "t";
cin.ignore();
cin.get();
}
谢谢你们的帮助。
您有3个错误:
- 正如@Lukasz P.在评论中提到的,
int* ptr
应该指向数组arr
,int* ptr = arr;
- 您访问最后一个元素的越界(当
j = 8
时) -
你需要继续排序,直到没有更多的交换:
bool sorted = false; // keep track here whether you still need to sort int *ptr = arr; while (!sorted) // repeat this until no more swaps { sorted = true; for (int j = 0; j < 8 ; j++) // Repeat until N - 1 (i.e. 8 in this case) { if (*(ptr + j ) > *(ptr + j + 1)) // make sure you don't access out of bounds { int temp = *(ptr + j); *(ptr + j) = *(ptr + j + 1); *(ptr + j + 1) = temp; sorted = false; // we swapped, so keep sorting } } }
相关文章:
- 如何在C++中对数组进行冒泡排序
- C++为什么我的指针选择排序中存在分段错误?
- 我想在 c++ 中对单向链表进行冒泡排序,但我一直面临左值错误,无法解决它
- 在C++中使用冒泡排序时出现意外值
- 冒泡排序中所需的交换次数,而无需实际对其进行排序
- 如何对文件中数组中的单个列进行冒泡排序?C++
- 对元素的向量或指向元素的指针进行排序
- 需要关于如何将我的随机数数组连接到冒泡排序的帮助
- 智能指针的排序向量:神秘崩溃
- 字符串指针的排序向量
- 冒泡排序无法对C++中的对象的动态数组进行排序
- 使用来自 unique_ptr 向量的原始指针作为排序的 ID
- 使用 std::sort 对自定义类的智能指针进行排序
- 使用智能指针进行排序时出现问题
- 冒泡排序.C++
- 链表的冒泡排序
- 有没有选择排序优于冒泡排序的输入
- C++类指针的排序与重载运算符<
- C++中基于指针的冒泡排序
- 使用交换函数和指针的c++冒泡排序