【问题标题】:Is there a more efficient way to sort integers using pointers WITHOUT using an array? [duplicate]有没有更有效的方法来使用指针而不使用数组对整数进行排序? [复制]
【发布时间】:2014-02-23 21:45:06
【问题描述】:

有没有更有效的方法来完成我在这里所做的事情?也许不必使用这么多 if 语句。

//This function takes the references of the values inputed and sorts them
//in ascending order without returning anything.
void sortFunction(int *fptrOne, int *fptrTwo, int *fptrThree){

//Variables to hold max min and mid values
int max, min, mid;

//Series of if statements to determine max min and mid values.
if(*fptrOne < *fptrTwo && *fptrOne < *fptrThree)
    min = *fptrOne;
    else if(*fptrTwo < *fptrOne && *fptrTwo < *fptrThree)
        min = *fptrTwo;
        else if (*fptrThree < *fptrOne && *fptrThree < *fptrTwo)
            min= *fptrThree;

if(*fptrOne > *fptrTwo && *fptrOne > *fptrThree)
    max = *fptrOne;
    else if(*fptrTwo > *fptrOne && *fptrTwo > *fptrThree)
        max = *fptrTwo;
        else if (*fptrThree > *fptrOne && *fptrThree > *fptrTwo)
            max = *fptrThree;

if(*fptrOne != max && *fptrOne != min)
    mid = *fptrOne;
    else if(*fptrTwo != max && *fptrTwo != min)
        mid = *fptrTwo;
        else if(*fptrThree != max && *fptrThree != min)
            mid = *fptrThree;

//Assign min mid and max to pointers in ascending order
*fptrOne = min;
*fptrTwo = mid;
*fptrThree = max;

}

【问题讨论】:

标签: c function sorting pointers


【解决方案1】:

使用sorting network

void sortFunction(int *fptrOne, int *fptrTwo, int *fptrThree)
{
    int x = *fptrOne, y = *fptrTwo, z = *fptrThree, tmp;

    if(y>z) { tmp = y; y = z; z = tmp; }
    if(x>z) { tmp = x; x = z; z = tmp; }
    if(x>y) { tmp = x; x = y; y = tmp; }

    *fptrOne = x;
    *fptrTwo = y;
    *fptrThree = z;
}

【讨论】:

  • 要交换两个整数,也可以使用{ a ^= b; b ^= a; a ^= b; } 块,而不必使用临时载体变量,即tmp
  • @ThoAppelsin:这个建议在几年前可能是有道理的,但有good reasons to avoid XOR swap in practice
【解决方案2】:

是的。最好(或至少最简单)的方法是首先对第一个成员进行排序,然后是第二个,然后(隐含地,因为第一个和第二个是排序的)最后。

// I'm lazy. Swaps a and b.
void swapInt(int* a, int* b) { int tmp = *a; *a = *b; *b = tmp; }

void sortFunction(int* a, int* b, int* c)
{
    if(*a > *b) swap(a, b);
    if(*a > *c) swap(a, c); // a is now smallest
    if(*b > *c) swap(b, c);
}

这里可以做一些小的优化,但这是一个开始,应该让您知道如何继续。

【讨论】:

    【解决方案3】:

    您可以使用简单的sorting network,例如

    void Sort2(int *p0, int *p1)
    {
        if (*p0 > *p1)
        {
            int temp = *p0;
            *p0 = *p1;
            *p1 = temp;
        }
    }
    
    void Sort3(int *p0, int *p1, int *p2)
    {
        Sort2(p0, p1);
        Sort2(p1, p2);
        Sort2(p0, p1);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-01-08
      • 1970-01-01
      • 2019-12-08
      • 1970-01-01
      • 2016-02-04
      • 1970-01-01
      相关资源
      最近更新 更多