将元素插入数组

编程入门 行业动态 更新时间:2024-10-27 11:17:14
本文介绍了将元素插入数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

如何使用inset方法以正确的顺序将数字添加到数组中?

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

更多推荐

将元素插入数组

本文发布于:2023-10-26 11:39:28,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1530029.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   元素

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!