如何根据指向的值对双指针数组进行排序?

Ed.*_*Ed. 2 c c++ arrays pointers reference

我试图在C/C++中构建一个函数来对数组进行排序,并用它的"得分"或排名替换每个值.它将一个双指针数组接收到一个int数组,并根据整数的解除引用值对双指针进行排序.我已经尝试了很多次才能使它工作,但不能让它失效.它必须再次根据它们指向的值对双指针进行排序.这就是我所拥有的:

void SortArray( int ** pArray, int ArrayLength )
{
  int i, j, flag = 1;     // set flag to 1 to begin initial pass
  int * temp;             // holding variable orig with no *
  for(i = 1; (i <= ArrayLength) && flag; i++)
  {
    flag = 0;
    for (j = 0; j < (ArrayLength -1); j++)
    {
        if (*pArray[j+1] > *pArray[j])    // ascending order simply changes to <
        { 
            temp = &pArray[j];            // swap elements
            pArray[j] = &pArray[j+1];
            pArray[j+1] = &temp;
            flag = 1;                     // indicates that a swap occurred.
        }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

OJ.*_*OJ. 5

你很亲密 您在交换时引用了数组项的地址,这是不必要的.数组中的项是指针,这是需要交换的内容.

见下文:

void SortArray( int ** pArray, int ArrayLength )
{
    int i, j, flag = 1;    // set flag to 1 to begin initial pass
    int * temp;             // holding variable orig with no *
    for(i = ArrayLength - 1; i > 0 && flag; i--)
    {
        flag = 0;
        for (j = 0; j < i; j++)
        {
            if (*pArray[j] > *pArray[j+1])      // ascending order simply changes to <
            { 
                temp = pArray[j];             // swap elements
                pArray[j] = pArray[j+1];
                pArray[j+1] = temp;
                flag = 1;               // indicates that a swap occurred.
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

另外,如果你感兴趣的话,请查看这篇关于Bubble Sorting的可爱博客文章(对不起,无耻的插件:)).希望能帮助你完成作业;)


编辑:注意细微的"优化",从数组长度开始计算,并且只在内循环中递增到"i".这样可以避免不必要地重新排序已经排序的项目.