02 Arrays
02 Arrays
Array
Contents
Array
Subscript or Index of Array
Length or Size of Array
Declaring An Array
Types of Arrays
o One Dimension or linear Array
o Multi-Dimensional Array
Memory Representation
o Static Memory Allocation
o Dynamic Memory Allocation
Operations on Arrays
Main Function
Advantages of Array
Disadvantages of Array
Vector
Array
Arrays are probably the most common data structure used to store collections of elements.
An array is a collection of same data types which occupies contiguous memory locations. The
elements to be placed in an array must be of same data type and there should be contiguous
memory locations for allocation of arrays. Arrays are frequently used to store relatively
permanent data, as it is easy to traverse, search and sort. If size of structure and data are
constantly changing, Arrays are not preferred.
Subscript or Index of Array
Each Array element is referenced by a single subscript or index. Subscript or Index is a
number used to refer an Array element. In most languages, arrays are convenient to declare and
provide the handy [ ] syntax to access any element by its index number. Array indices normally
1/9
Lecture Notes Data Structures and Algorithms
start from 1 whereas in C++ it starts with 0. The arrays in which array index begins at 0 are
called regular arrays and the arrays in which index begins with any other number (mostly 1) are
called non-regular arrays.
Declaring An Array
Array declaration in C++ has three parts
• The name of Array
• The data type of Array
• The length of Array
Examples
int arr[20];
Where name if array is arr, its data type is integer and its length is 20.
Types of Arrays
There are two types of Arrays.
1. One Dimension or linear Array
In One-Dimensional or Linear Array each Array element is referenced by a single subscript.
2. Multi-Dimensional Array
The Arrays referenced by more than one subscript.
2/9
Lecture Notes Data Structures and Algorithms
Memory Representation
There are two types of memory representations for arrays.
1. Static Memory Allocation
Memory is allocated for Array during compilation and size of Array is fixed during execution
of the Program. For example FORTRAN, Pascal and C support static memory allocation for
arrays.
2. Dynamic Memory Allocation
Dynamic Memory Allocation allows one to read an integer, say n, and then declares an Array
of n elements dynamically at runtime. For example: Java and C++ supports dynamic memory
allocation.
Operations on Arrays
Following are the major operations to manipulate array.
class myArray{
private:
int a[10];
int N; // numbers of elements in a
public:
myArray(){
N=0;
for(int i=0; i<10; i++)
a[i]=NULL;
}
void traverse();
void Insert();
void InsertAtStart();
void InsertAtEnd();
void Delete();
void DeleteStart();
void DeleteEnd();
void LinearSearch();
void BinarySearch();
void BubbleSort();
void Merge();
};
1. Traversing
The C++ code for traversing of an array is as follows.
void myArray :: traverse() {
for (i=0; i < N; i++) // traverse each element of array
cout << a[i] << endl;
3/9
Lecture Notes Data Structures and Algorithms
2. Insertion
The C++ code for insertion of an element in a specified location in array is as follows.
void myArray :: Insert() {
if (N == 10) { // to check overflow
cout << “Array is full”;
return;
}
int i, num, ind; // N is index of last element in “a”
do {
cout << endl << “Enter the index to delete: “;
cin >> ind; // must be from 0 to 9
} while (ind<0 || ind >N-1);
cout << endl << “Enter a number to insert: “;
cin >> num;
for (i=N-1; i >= ind; i--) // shift element of array one
a[i+1] = a[i]; // starting from ind
a[ind] = num;
N++;
}
3. Insert at Start
The C++ code for insertion of an element at start of array is as follows.
void myArray :: InsertAtStart() {
if (N == 10) { // to check overflow
cout << “Array is full”;
return;
}
int i, num, ind=0; // N is index of last element in “a”
cout << endl << “Enter a number to insert: “;
cin >> num;
for (i=N-1; i >= ind; i--) // shift element of array one
a[i+1] = a[i]; // starting from ind
a[ind] = num;
N++;
}
4. Insert At End
The C++ code for insertion of an element at end of array is as follows.
void myArray :: InsertAtEnd() {
if (N == 10) { // to check overflow
cout << “Array is full”;
return;
}
int num; // N is index of last element in “a”
cout << endl << “Enter a number to insert: “;
4/9
Lecture Notes Data Structures and Algorithms
5. Deletion
The C++ code for deletion of an element from array is as follows.
void myArray :: Delete() {
if (N == 0) { // to check underflow
cout << “Array is empty”;
return;
}
int i, ind;
do {
cout << endl << “Enter the index to delete: “;
cin >> ind; // must be from 0 to 9
} while (ind<0 || ind >N-1);
for (i=ind; i < N-1; i++) // traverse each element of array
a[i] = a[i+1]; // override element of ind
a[N-1]=NULL;
N--;
}
6. Delete Start
The C++ code for deletion of an element from start of array is as follows.
void myArray :: DeleteStart() {
if (N == 0) { // to check underflow
cout << “Array is empty”;
return;
}
int i, ind=0;
for (i=ind; i < N-1; i++) // traverse each element of array
a[i] = a[i+1]; // override element of ind
a[N-1]=NULL;
N--;
}
7. Delete End
The C++ code for deletion of an element from end of array is as follows.
void myArray :: DeleteEnd() {
if (N == 0) { // to check underflow
cout << “Array is empty”;
return;
}
a[N]=NULL;
N--;
5/9
Lecture Notes Data Structures and Algorithms
8. Searching
The C++ code for searching of an element in an array using linear search is as follows.
void myArray :: LinearSearch() {
if (N == 0) { // to check underflow
cout << “Array is empty”;
return;
}
int i, num, flag=0;
cout << endl << “Enter a number to search: “;
cin >> num;
for (i=0; i < N; i++)
if(num == a[i]) {
cout << “element is found at index ” << i;
flag=1;
}
if (flag == 0)
cout << “Item not found”;
}
Algorithm to search for an element from a sorted sequence is called Binary Search. The C++ code for
Binary Search is as follows.
void myArray :: BinarySearch() {
if (N == 0) { // to check underflow
cout << “Array is empty”;
return;
}
int i, j, Center, MAXINDEX=N-1, MININDEX=0, loc=0;
BubbleSort();
/* Binary search. */
while (MAXINDEX >= MININDEX) {
Center=(MAXINDEX+MININDEX)/2;
if (num==a[Center]) {
loc=1;
break;
}
if (num<a[Center])
MAXINDEX=Center-1;
else
MININDEX=Center+1;
}
if (loc==1)
cout << “Number found at index ” << Center;
else
6/9
Lecture Notes Data Structures and Algorithms
9. Sorting
The C++ code for sorting of an array using Bubble S is as follows.
void myArray :: BubbleSort() {
if (N == 0) { // to check underflow
cout << “Array is empty”;
return;
}
int temp, i, j, s;
10.Merging
The C++ code for merging of two arrays is as follows.
void myArray :: Merge() {
int i, j;
int a[5], b[5]; // array “mArr” of 10 integers is for
// merging a and b
cout << endl << “Enter five number for first array: “;
for (i=0; i < 5; i++) // get numbers for array “a”
cin >> a[i];
cout << endl << “Enter five number for second array: “;
for (i=0; i < 5; i++) // get numbers for array “b”
cin >> b[i];
7/9
Lecture Notes Data Structures and Algorithms
Main Function
int main () {
myArray arr;
arr.InsertAtStart();
arr.InsertAtEnd();
arr.InsertAtStart();
arr.InsertAtEnd();
arr.Insert();
arr.traverse();
arr.deleteStart();
arr.deleteEnd();
arr.delete();
arr.LinearSearch();
arr.BinarySearch();
arr.BubbleSort();
arr.Merge();
}
Advantages of Arrays
Following are the major advantages of arrays.
Easy to access an element directly using index.
Efficient in searching and sorting.
Disadvantages of Arrays
Following are the major disadvantages of arrays.
The size of the array is fixed and most often this size is specified at compile time with a
simple declaration. With a little extra effort, the size of the array can be deferred until the
array is created at runtime, but after that it remains fixed. You can go to the trouble of
dynamically allocating an array in the heap and then dynamically resizing it with
realloc(), but that requires some real programmer effort.
The most convenient thing for programmers to do is to allocate arrays which seem "large
enough" (e.g. the 100 in the scores example). Although convenient, this strategy has two
disadvantages: (a) most of the time there are just 20 or 30 elements in the array and 70%
of the space in the array really is wasted. (b) If the program ever needs to process more
than 100 scores, the code breaks.
Inserting new elements at front is potentially expensive because existing elements need to
be shifted over to make room. Same as the case with deletion of a single element in array.
8/9
Lecture Notes Data Structures and Algorithms
Vector
The elements of a vector are stored contiguously. Like all dynamic array implementations,
vectors have low memory usage and good locality of reference and data cache utilization. Unlike
other Standard Template Library containers, such as deques and lists, vectors allow the user to
denote an initial capacity for the container.
Vectors allow random access; that is, an element of a vector may be referenced in the same
manner as elements of arrays (by array indices). Linked-lists and sets, on the other hand, do not
support random access. The vector data structure is able to quickly and easily allocate the
necessary memory needed for specific data storage. This is particularly useful for storing data in
lists whose length may not be known prior to setting up the list but where removal (other than,
perhaps, at the end) is rare. Erasing elements from a vector or even clearing the vector entirely
does not necessarily free any of the memory associated with that element.
9/9