next up previous contents
Next: Lists: ADT Up: Arrays: Abstract Data Type Previous: Arrays: Abstract Data Type   Contents

Arrays [3]



\begin{center}\vbox{\input{array.latex}
}\end{center}



The ARRAY Abstract Data Type has the following operations:

ARRAY create_array(int max_size);
int is_empty(ARRAY A);
int is_full(ARRAY A);
position find(element_type x, ARRAY A);
void insert(element_type x, ARRAY A, position p);

The ARRAY object is only accessed using these functions.

The implementation is hidden from other functions.

After ``create'', maximum size does not change (STATIC).

To insert ``e'' at position p, SHIFT RIGHT.

WORST CASE: might have to move ``n'' keys to the right.

Big-Oh of n, or Oh of n, or Order n: O(n)



Arrays: array [4]

% gcc -o array array.c                    [> dos.bat]    > tcc array.c
% array
> h
h(elp; q(uit; i(nsert x pos; f(ind x; d(isplay
> q

Data File with Test Cases: array.dat

i h 0 d
i l 1 d
i o 2 d
i e 1 d
i l 2 d
q

Run Test Cases: %array array.dat

Array: h 
Array: h l 
Array: h l o 
Array: h e l o 
Array: h e l l o



Arrays: array.c [5]

#define NIL -1
typedef char element_type;
struct array_record {
  unsigned int max_size;
  unsigned int size;
  element_type *array;
};
typedef struct array_record *ARRAY;
typedef int position;
ARRAY create_array(int max_size) {
ARRAY A;
  A = (ARRAY) malloc(sizeof(struct array_record));
  if (A == NULL)
    printf("Out of space!\n");
  else {
    A->array = (element_type *) malloc(sizeof(element_type)*(max_size));
    if (A->array == NULL)
      printf("Out of space!\n");
    else {
      A->max_size = max_size;
      A->size = 0;
    }
  }
  return(A);
}


Arrays: array.c [6]
int is_empty(ARRAY A) {
  return(A->size == 0);
}
int is_full(ARRAY A) {
  return(A->size == A->max_size);
}
position find(element_type x, ARRAY A) {
position p;
  for (p=0; p<A->size; p++)
    if (A->array[p] == x)
      return p;
  return NIL;
}
void insert(element_type x, ARRAY A, position p) {
position p1;
  if (is_full(A))
    printf("Array is full\n");
  else {
    for (p1=A->size; p1>p; p1--)
      A->array[p1] = A->array[p1-1];
    A->array[p] = x;
    A->size++;
  }
}



Ted Billard 2001-10-25