将元素插入一个数组 [英] Inserting an element into an array

查看:123
本文介绍了将元素插入一个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎样才能让一个嵌入方法,将按照正确的顺序添加一个数字数组?

How can I make an inset method that will add a number into the array in the correct order?

void addElement(int table[], int element, int length) {
    int x = 0;
    int temporary=0;
    cout<<length<<endl;

    if(length == 1) {
        table[0] = element;
    }
    else {
        if(length == 2) {
            if (table[0] > element) {
               int temp = table[0];
               table[0] = element;
               table[1] = temp;
            }
            else {
                table[1] = element;
            }
        }
        else {
            for(int i = 0; i< length && x == 0; i++) {
                if(element<table[i] && element>=table[i-1]) {
                    for(int y = i; y<length; y++) {
                        temporary = table[y+2];
                        int temp = table[y];
                        table[y] = element;
                        table[y+1] = table
                     }
                }
            }
        }
    }
}

这是据我已经得到了。在我的主类我已经做出来,以便阵列增加1所以有在数组的最后一个打开的空间,一切由1推后。

This is as far as I have gotten. In my main class I have worked it out so that array is increased by 1. So there is one open space at the end of the array for everything to be pushed back by 1.

推荐答案

您可以从后向前扫描阵列,同比移动值,直到你找到正确的插入点。

You can scan the array from back to front, moving values up until you find the correct insertion point.

void addElement(int *table, int element, int length)
{
    int i = length - 1;
    for (; i > 0 && table[i-1] > element; --i)
    {
        table[i] = table[i-1];
    }
    table[i] = element;
}

这篇关于将元素插入一个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆