是否有更有效的方法使用指针排序整数而不使用数组?

时间:2014-02-23 21:45:07

标签: c function sorting pointers

有没有更有效的方法来完成我在这里所做的事情?也许不必使用这么多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;

}

3 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分:1)

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

// 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);
}

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

答案 2 :(得分:1)

您可以使用简单的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);
}