通过提供指针数组作为参数对数组进行排序

Sorting an array by providing an array of pointers as arguments

本文关键字:数组 参数 排序 指针      更新时间:2023-10-16

我写了这段代码,但它只给了我一个地址:

#include<iostream>
using namespace std;
void swap(int* a,int* b) 
{
    int temp=*a;
    *a=*b;
    *b=temp;
}
void sort(int* p[],int n) 
{
    for(int i=0; i<n;i++)
    {
        if(*p[i]>*p[i+1])
        swap(p[i],p[i+1]);
    }
}
int main()
{
    int arr[]={8,6,5,4,3,7,1};
    int* p[7];
    for(int i=0;i<7;i++)
    {
        p[i]=&arr[i];
    }
    sort(p,7);
    /*i tried to change arr[1] to p[1] or *p[1] but same output*/
    cout<<arr[1]<<arr[2];
    return 0;
}

我想我在某处缺乏概念。完整的问题是:

编写以下函数,通过重新排列指针间接排序数组 p 中前 n 个指针指向的浮点数:void sort(float* p[],int n(

请帮忙。

这是一种更好的方法来做你想做的事情,有很多方法可以做得更好,但它看起来像你对 c++ 的新手,所以我试图让它尽可能简单。

#include "stdafx.h"
#include<iostream>
using namespace std;
//not needed, std::swap does the same job!
void swap(int *a, int *b)
{
    std::swap(a, b);
}
//using a pointer to the array is better!
void sort(int arr[], int n)
{
    //two loops are needed to sort the entire array!
    for (int x(0); x < n - 1; x++)
    {
        //optimize the loop by removing already sorted items from loop
        int sorted = n - x;
        for (int y(0); y < sorted - 1; ++y)
            if (arr[y] > arr[y + 1])
                std::swap(arr[y], arr[y + 1]);
    }
}

int main()
{
    //vector or std::array better option!
    int arr[] { 8,6,5,4,3,7,1 };
    //provide the array to sort(), no need to make stuff harder
    sort(arr, 7);
    //Show you that the sort worked!
    for (int ccc = 0; ccc < 7; ccc++)
        std::cout << arr[ccc] << ' ';
    std::cout << 'n';
    cout << "Index 5: " << arr[5] << "nIndex 6: " << arr[6] << "n";
    return 0;
}

这里有一个非常好的数组排序教程:http://www.learncpp.com/cpp-tutorial/64-sorting-an-array-using-selection-sort/

首先,您的代码具有缓冲区溢出,这意味着未定义的行为,因此根据定义,它所做的任何事情都是正确的。在sort索引i遍历从 0 到 n-1 的所有数组位置。但是你访问i+1,这是数组之外的一个元素。对我来说,代码段错误。

更正后,输出为"54",这是发生的事情。

swap 函数交换arr中的值,而不是交换p中的指针。该练习要求您间接对数组进行排序,从而威胁指针。你需要在那里使用**或*&。因此,在排序循环中发生的情况是交换 8 和 6,然后交换 8 和 5,交换 8 和 4,依此类推。所以你的数组是 {6,5,4,3,7,1,8}。最后输出 arr[1] 和 [2],即 5 和 4。由于您没有在它们之间输出空格,因此您会得到"54"。