C++中基于指针的冒泡排序

Pointer Based Bubble Sort in C++

本文关键字:指针 冒泡排序 于指针 C++      更新时间:2023-10-16

我一直在尝试使用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个错误:

  1. 正如@Lukasz P.在评论中提到的,int* ptr应该指向数组arrint* ptr = arr;
  2. 您访问最后一个元素的越界(当j = 8时)
  3. 你需要继续排序,直到没有更多的交换:

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