C - 将数字插入数组并维护排序顺序

时间:2017-01-22 01:55:06

标签: c arrays

我正在尝试创建一个程序,它能够将整数插入到数组中并维护其排序顺序。即每次插入一个数字时,它都会循环遍历数组以找到它应该插入的位置,将每个元素推到一个索引上,以便为插入腾出空间,然后插入值。无论出于何种原因,我似乎无法解决这个问题。如果有人能提供任何见解或帮助,我们将非常感激。

struct data
{
    int numbers[10];
    int length;
};

void insert(struct data *x, int newNumber);


void insert(struct data *x, int newNumber)
{
    int i, k;

    if(x->length == 0)
    {
        x->length++;
        x->numbers[0] = newNumber;
    }

    // Increase Length
    x->length = x->length + 1;

    // Loop Through the array
    for(i = 0; i < x->length; i++)
    {
        // Find location where newNumber should come after
        if(x->numbers[i] < newNumber)
        {
            // Shift each element until i
            for(k = x->length-1; k > i; k--)
            {   
                x->numbers[k+1] = x->numbers[k];
            }

            // Set next element equal to newNumber
            x->numbers[k] = newNumber;
        }
    }
}

2 个答案:

答案 0 :(得分:1)

像这样修复

#include <stdio.h>

#define MAX_ELEMENT_LENGTH 10

struct data {
    int numbers[MAX_ELEMENT_LENGTH];
    int length;
};

void insert(struct data *x, int newNumber){
    int i, k;

    if(x->length == 0){
        x->numbers[x->length++] = newNumber;
    } else if(x->length < MAX_ELEMENT_LENGTH){//need this check
        //x->length = x->length + 1;//Do not increment before the loop. because x->numbers[i] occurs out of bounds

        for(i = 0; i < x->length; i++){   //descending order
            if(x->numbers[i] < newNumber){//descending order
                //insert position is i
                for(k = x->length-1; k >= i; k--){//k > i --> k >= i
                    x->numbers[k+1] = x->numbers[k];
                }
                break;//exit loop
            }
        }
        x->numbers[i] = newNumber;
        x->length++;
    }
}

int main(void){
    //DEMO
    struct data x = { {0}, 0 };

    insert(&x, 5);
    for(int i = 1; i < 11; ++i)
        insert(&x, i);

    for(int i = 0; i < x.length; ++i)
        printf("%d ", x.numbers[i]);
    puts("");
    return 0;
}

答案 1 :(得分:0)

BLUEPIXY的回应对解决这个问题非常有帮助。再次感谢。

select <column name>