一、数组。
1.思想:
2.特点:
- ①内存是连续的。
- ②数组中的元素通过下标进行访问,数组下标从0开始。
- ③数组中的元素本身可以是具有某种结构的数据,但属于同一数据类型。
3.优点:
4.缺点:
- ①数组的大小一旦确定不能进行扩容。
- ②数组只能存储同类型的数据。
- ③数组在进行添加、删除等操作时速度慢。
5.适用场景:
- ①频繁查找。
- ②对于存储空间要求不大。
- ③很少进行添加、删除等操作。
6.C语言代码实现:
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#define MAX_Array_DIM 5
typedef int ElemType;
typedef struct {
ElemType *base;
int dim;
int *bounds;
int *constants;
}Array;
Status InitArray(Array *A, int dim, ...) {
int elemtotal;
va_List ap;
int i;
if (dim<1 || dim>MAX_Array_DIM)
return ERROR;
A->dim = dim;
A->bounds = (int*)malloc(dim*sizeof(int));
if (!A->bounds)
return OVERFLOW;
elemtotal = 1;
va_start(ap, dim);
for (i=0; i<dim; i++) {
A->bounds[i] = va_arg(ap, int);
if (A->bounds[i] <= 0)
return UNDERFLOW;
elemtotal *= A->bounds[i];
}
va_end(ap);
A->base = (ElemType*)malloc(elemtotal*sizeof(ElemType));
if (!A->constants)
return OVERFLOW;
A->constants[dim-1] = 1;
for (i=dim-2; i>=0; i--)
A->constants[i] = A->bounds[i+1] * A->constants[i+1];
return OK;
}
Status DestroyArray(Array *A) {
if (!A->base)
return ERROR;
free(A->base);
A->base = NULL;
if (!A->bounds)
return ERROR;
free(A->bounds);
A->bounds = NULL;
if (!A->constants)
return ERROR;
free(A->constants);
A->constants = NULL;
A->dim = 0;
return OK;
}
Status ValueArray(Array A, ElemType *e,···) {
va_List ap;
Status result;
int off;
va_start(ap, *e);
result = LocateArray(A, ap, &off);
if (result = OVERFLOW)
return result;
*e = *(A.base + off);
return OK;
}
Status AssignArray(Array *A, ElemType e, ···) {
va_List ap;
Status result;
int off;
va_start(ap, e);
result = LocateArray(*A, ap, &off);
if (result = OVERFLOW)
return result;
*(A->base+off) = e;
return OK;
}
7.JavaScript代码实现:
var a = [1, 2, 3, 4, 5];
var arr = new Array(10);
文件名称:Array.js
*作 者:末子灬秋风
*完成时间:2021年1月12日
*
*/
var a = [1, 2, 3, 4, 5];
var arr = new Array(10);