数组中的元素转移 [英] Shifting Elements in an Array

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

问题描述

我有对象的数组,而我想拉一个元素顶端,其余向下一班。

I have an array of objects, and I am trying to pull one element to the top and shift the rest down by one.

假设我有大小为10的数组,我试图拉第五元素。第五元素进入位置 0 从0到5的所有元素将一个下移。

Assume I have an array of size 10, and I am trying to pull the fifth element. The fifth element goes into position 0 and all elements from 0 to 5 will be shifted down by one.

我的算法是行不通的。从逻辑上讲,它应该工作。是否有人可以来看看吗?假设位置是我想拉到阵列顶部的位置。

My algorithm is not working. Logically, it should work. Can someone please take a look at it? Assume position is the position I want to pull to the top of the array.

Object temp = pool[position];

for (int i = 0; i < position; i++) {                
    array[i+1] = array[i];
}

array[0] = temp;

感谢您

推荐答案

假设你的数组是{10,20,30,40,50,60,70,80,90,100}

Assuming your array is {10,20,30,40,50,60,70,80,90,100}

你的循环作用是:

迭代1:数组[1] =阵列[0]; {10,10,30,40,50,60,70,80,90,100}

Iteration 1: array[1] = array[0]; {10,10,30,40,50,60,70,80,90,100}

迭代2:阵列[2] =阵列[1]; {10,10,10,40,50,60,70,80,90,100}

Iteration 2: array[2] = array[1]; {10,10,10,40,50,60,70,80,90,100}

你应该做的是

Object temp = pool[position];

for (int i = (position - 1); i >= 0; i--) {                
    array[i+1] = array[i];
}

array[0] = temp;

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

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