学习笔记:Java数组和递归。

来源:互联网 发布:农村经济数据 编辑:程序博客网 时间:2024/05/19 04:51

程序由指令和数据组成。细想这句话,指令可以理解为逻辑,先放下不谈。数据就是数据,没什么好解释的,可是,数据如何存放、组织、管理便是一个新的问题。程序要能正常的读取和操作数据,就需要将数据合理的组织起来,形成一定的结构,即“数据结构”。

维基百科关于数据结构的解释:

在计算机科学中,数据结构(英语:data structure)是计算机中存储、组织数据的方式。
常见的数据结构有:
数组(Array)
堆栈(Stack)
队列(Queue)
链表(Linked List)
树(Tree)
图(Graph)
堆(Heap)
散列表(Hash)

今天学习了第一个,也是相对简单的数据结构,数组。

定义数组

例:

int[] array;//数据常用的两种初始化方法。array = new int[10];array = new int[]{1,3,5,7,9}

数组四大操作:增、删、改、查。

1、增,插入一个元素

数组在初始化的时长度便已固定,如果数组还有存储空间,可以在长度内任意位置直接插入元素,但别忘了将后面的元素依次后移。如果空间已没有,便需要扩容.Java数组扩容采用建立一个新的数组,然后将原数据的数据拷贝过来。这里需要用到函数System.arraycopy。

public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length)

Dcription:
The java.lang.System.arraycopy() method copies an array
from the specified source array, beginning at the specified position,
to the specified position of the destination array. A subsequence of
array components are copied from the source array referenced by src to
the destination array referenced by dest.The number of components
copied is equal to the length argument.

The components at positions srcPos through srcPos + length - 1 in the
source array are copied into positions destPos through destPos +
length - 1, respectively, of the destination array.

Parameters :
src − This is the source array.

srcPos − This is the starting position in the source array.

dest − This is the destination array.

destPos − This is the starting position in the destination data.

length − This is the number of array elements to be copied.

2、删

同“插入”操作一样,办法很多,最简便的依次将元素前移一位。

3、改和查

没多少记录的,数据改的复杂度多事O(1),直接定位过去改就行。

递归

今天上Google搜递归,还被调戏了一把,关于递归,有个很牛逼的解释:包子馅的包子,极限就是馒头。从以前到现在,递归的概念一直都是理解的,可是实际写的很少。知道递归就是自己调用自己,然后必须要收敛,不收敛的递归会造成死循环,可是今天就是用递归实现冒泡排序算法都做不到,还要勤加练习。

原创粉丝点击