Basic Operations of Array
Basic Operations of Array
Basic Operations of Array
Array is a container which can hold a fix number of items and these items should be of the
same type. Most of the data structures make use of arrays to implement their algorithms.
Following are the important terms to understand the concept of Array.
Element − Each item stored in an array is called an element.
Index − Each location of an element in an array has a numerical index, which is used
to identify the element.
Array Representation
Arrays can be declared in various ways in different languages. For illustration, let's take C
array declaration.
Arrays can be declared in various ways in different languages. For illustration, let's take C
array declaration.
As per the above illustration, following are the important points to be considered.
Index starts with 0.
Array length is 10 which means it can store 10 elements.
Each element can be accessed via its index. For example, we can fetch an element at
index 6 as 9.
bool false
char 0
int 0
float 0.0
double 0.0f
void
Traverse Operation
Example
Output
Insertion Operation
Insert operation is to insert one or more data elements into an array. Based on the
requirement, a new element can be added at the beginning, end, or any given index of array.
Here, we see a practical implementation of insertion operation, where we add data at the end
of the array −
Example
main() {
int LA[] = {1,3,5,7,8};
int item = 10, k = 3, n = 5;
int i = 0, j = n;
n = n + 1;
while( j >= k) {
LA[j+1] = LA[j];
j = j - 1;
}
LA[k] = item;
Output
Deletion Operation
Deletion refers to removing an existing element from the array and re-organizing all
elements of an array.
Algorithm
Example
void main() {
int LA[] = {1,3,5,7,8};
int k = 3, n = 5;
int i, j;
j = k;
while( j < n) {
LA[j-1] = LA[j];
j = j + 1;
}
n = n -1;
Output
Search Operation
You can perform a search for an array element based on its value or its index.
Algorithm
Example
void main() {
int LA[] = {1,3,5,7,8};
int item = 5, n = 5;
int i = 0, j = 0;
j = j + 1;
}
Output
Update Operation
Update operation refers to updating an existing element from the array at a given index.
Algorithm
Example
void main() {
int LA[] = {1,3,5,7,8};
int k = 3, n = 5, item = 10;
int i, j;
printf("The original array elements are :\n");
LA[k-1] = item;
Output
We take an unsorted array for our example. Bubble sort takes Ο(n 2) time so we're
keeping it short and precise.
Bubble sort starts with very first two elements, comparing them to check which one
is greater.
In this case, value 33 is greater than 14, so it is already in sorted locations. Next, we
compare 33 with 27.
We find that 27 is smaller than 33 and these two values must be swapped.
Next we compare 33 and 35. We find that both are in already sorted positions.
We swap these values. We find that we have reached the end of the array. After
one iteration, the array should look like this −
To be precise, we are now showing how an array should look like after each
iteration. After the second iteration, it should look like this −
Notice that after each iteration, at least one value moves at the end.
And when there's no swap required, bubble sorts learns that an array is completely
sorted.
Algorithm
We assume list is an array of n elements. We further assume that swap function
swaps the values of the given array elements.
Algorithm BubbleSort(list)
{
for all elements of list
if list[i] > list[i+1]
swap(list[i], list[i+1])
end if
end for
return list
}
Pseudocode
We observe in algorithm that Bubble Sort compares each pair of array element unless the
whole array is completely sorted in an ascending order. This may cause a few complexity
issues like what if the array needs no more swapping as all the elements are already
ascending.
To ease-out the issue, we use one flag variable swapped which will help us see if any swap
has happened or not. If no swap has occurred, i.e. the array requires no more processing to
be sorted, it will come out of the loop.
Pseudocode of BubbleSort algorithm can be written as follows −
Algorithm bubbleSort( list : array of items )
{
loop = list.count;
end for
end for
return list
}
Implementation
One more issue we did not address in our original algorithm and its improvised
pseudocode, is that, after every iteration the highest values settles down at the end
of the array. Hence, the next iteration need not include already sorted elements.
int main()
{
int arr[100], i, n, step, temp;
// ask user for number of elements to be sorted
printf("Enter the number of elements to be sorted: ");
scanf("%d", &n);
// input elements if the array
for(i = 0; i < n; i++)
{
printf("Enter element no. %d: ", i+1);
scanf("%d", &arr[i]);
}
// call the function bubbleSort
bubbleSort(arr, n);
return 0;
}
Linear Search
What is Search?
Search is a process of finding a value in a list of values. In other words,
searching is the process of locating given value position in a list of values.
Example
Consider the following list of elements and the element to be searched...
Implementation of Linear Search Algorithm using C++ Programming Language
#include<iostream.h>
#include<conio.h>
void main()
{
int list[20],size, i, sElement;
cout<<”Enter size of the list: ";
cin>>size;
cout<<”Enter any”<<size<<” integer values: ";
for(i = 0; i < size; i++)
cin>>list[i];
cout<<"Enter the element to be Search: ";
cin>>sElement;
// Linear Search Logic
for(i = 0; i < size; i++)
{
if(sElement == list[i])
{
Cout<<"Element is found at”<<i<< “ index” ;
break;
}
}
if(i == size)
cout<<"Given element is not found in the list!!!";
getch();
}
Binary Search
Binary search algorithm falls under the category of interval search algorithms. This
algorithm is much more efficient compared to linear search algorithm. Binary
search only works on sorted data structures. This algorithm repeatedly target the
center of the sorted data structure & divide the search space into half till the match
is found.
The time complexity of binary search algorithm is O(Log n).
Binary search is implemented using following steps...
BSEARCH(ARR, LB, UB, ITEM, LOC)
{
/*Here, ARR is a sorted list of elements, with LB and UB are lower and upper
bounds for the array. ITEM needs to be searched in the array and algorithm
returns location LOC, index at which ITEM is present else return -1.*/
Algorithm
//Let array a[n] of elements in increasing order, n ≥0, determine whether ‘x’ is
present, and if so, set j, such that x = a[j] else return 0.
binsrch(a[], n, x)
{
low = 1; high = n;
while (low < high) do
{
mid = (low + high)/2
if (x < a[mid])
high = mid – 1;
else if (x > a[mid])
low = mid + 1;
else return mid;
} return 0;
}
Example:
Let’s say here, ITEM = 62
ARR[1] 2 3 4 5 6 7 8 9
BEG = 1 and END =9 Hence MID = (1+9)/2 = 5
ARR[MID]=ARR[5] = 52
6 7 8 9
Step 2: Now BEG =6 and END =9 thus MID = INT([6+9]/2)= 6
NOW ARR[6] =ITEM. Thus LOC = MID
ARR[6]=62 = ITEM =62,
Thus LOC = 6
BEG=MID+1=6+1=7
MID=7+9/2=16/2=8
ARR[8]==71
BEG 7, END =MID-1=7
ARR[7]= ITEM
71=71
The complexity of Binary Search
Here are the complexities of the binary search given below.
Worst Case: O(nlogn)
Best Case: O(1)
Average Case: O(nlogn)
Example 2
Consider-
We are given the following sorted linear array.
Element 15 has to be searched in it using Binary Search Algorithm.
Binary Search Algorithm works in the following steps-
Step-01:
To begin with, we take beg=0 and end=6.
We compute location of the middle element as-
mid
= (beg + end) / 2
= (0 + 6) / 2
=3
Here, a[mid] = a[3] = 20 ≠ 15 and beg < end.
So, we start next iteration.
Step-02:
Since a[mid] = 20 > 15, so we take end = mid – 1 = 3 – 1 = 2 whereas beg remains
unchanged.
We compute location of the middle element as-
mid
= (beg + end) / 2
= (0 + 2) / 2
=1
Here, a[mid] = a[1] = 10 ≠ 15 and beg < end.
So, we start next iteration.
Step-03:
Since a[mid] = 10 < 15, so we take beg = mid + 1 = 1 + 1 = 2 whereas end remains
unchanged.
We compute location of the middle element as-
mid
= (beg + end) / 2
= (2 + 2) / 2
=2
Here, a[mid] = a[2] = 15 which matches to the element being searched.
So, our search terminates in success and index 2 is returned.
Two-Dimensional Arrays
The simplest form of the multidimensional array is the two-dimensional array. A two-
dimensional array is, in essence, a list of one-dimensional arrays. To declare a two-
dimensional integer array of size x,y, you would write something as follows −
type arrayName [ x ][ y ];
Where type can be any valid C++ data type and arrayName will be a valid C++
identifier.
A two-dimensional array can be think as a table, which will have x number of rows
and y number of columns. A 2-dimensional array a, which contains three rows and
four columns can be shown as below −
#include <iostream.h>
int main () {
// an array with 5 rows and 2 columns.
int a[5][2] = { {7,4}, {1,2}, {2,4}, {3,6},{4,8}};
cout << "a[" << i << "][" << j << "]: ";
cout << a[i][j]<< endl;
}
return 0;
}
When the above code is compiled and executed, it produces the following result −
a[0][0]: 7
a[0][1]: 4
a[1][0]: 1
a[1][1]: 2
a[2][0]: 2
a[2][1]: 4
a[3][0]: 3
a[3][1]: 6
a[4][0]: 4
a[4][1]: 8
As explained above, you can have arrays with any number of dimensions, although
it is likely that most of the arrays you create will be of one or two dimensions.
Multi-dimensional array
A multi-dimensional array is an array of arrays. 2-dimensional arrays are
the most commonly used. They are used to store data in a tabular manner.
Consider following 2D array, which is of the size 3×5. For an array of
size N×M, the rows and columns are numbered from 0 to N−1 and columns are
numbered from 0 to M−1, respectively. Any element of the array can be
accessed by arr[i][j] where 0≤i<N and 0≤j<M. For example, in the following
array, the value stored at arr[1][3] is 14.
Pointers
#include<stdio.h>
int main()
int arr[3][4] = {
int (*ptr)[4];
ptr = arr;
return 0;
Output:
0x7ffead967560 0x7ffead967570 0x7ffead967580
0x7ffead967560 0x7ffead967570 0x7ffead967580
10 22 33
10 22 33
Record Structures
A record structure is an aggregate entity containing one or more elements.
(Record elements are also called fields or components.) You can use records
when you need to declare and operate on multi-field data structures in your
programs.
Examples
Intel Fortran record structures, using only intrinsic types, easily convert to
Fortran 95/90 derived types. The conversion can be as simple as replacing the
keyword STRUCTURE with TYPE and removing slash ( / ) marks. The
following shows an example conversion:
Record Structure
STRUCTURE /employee_name/
CHARACTER*25 last_name
CHARACTER*15 first_name
END STRUCTURE
STRUCTURE /employee_addr/
CHARACTER*20 street_name
INTEGER(2) street_number
INTEGER(2) apt_number
CHARACTER*20 city
CHARACTER*2 state
INTEGER(4) zip
END STRUCTURE
The record structures can be used as subordinate record variables within another
record, such as the employee_data record. The equivalent Fortran 90 derived
type would use the derived-type objects as components in a similar manner, as
shown below:
Record Structure
STRUCTURE /employee_data/
RECORD /employee_name/ name
RECORD /employee_addr/ addr
INTEGER(4) telephone
INTEGER(2) date_of_birth
INTEGER(2) date_of_hire
INTEGER(2) social_security(3)
LOGICAL(2) married
INTEGER(2) dependents
END STRUCTURE
C/C++ arrays allow you to define variables that combine several data items of
the same kind, but structure is another user defined data type which allows
you to combine data items of different kinds.
Structures are used to represent a record, suppose you want to keep track of
your books in a library. You might want to track the following attributes about
each book −
Title
Author
Subject
Book ID
Defining a Structure
To define a structure, you must use the struct statement. The struct statement
defines a new data type, with more than one member, for your program. The
format of the struct statement is this −
struct [structure tag]
{
member definition;
member definition;
...
member definition;
} [one or more structure variables];
The structure tag is optional and each member definition is a normal variable
definition, such as int i; or float f; or any other valid variable definition. At the
end of the structure's definition, before the final semicolon, you can specify
one or more structure variables but it is optional. Here is the way you would
declare the Book structure −
struct Books
{
char title[50];
char author[50];
char subject[100];
int book_id;
} book;
struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
};
int main() {
struct Books Book1; // Declare Book1 of type Book
struct Books Book2; // Declare Book2 of type Book
// book 1 specification
strcpy( Book1.title, "Learn C++ Programming");
strcpy( Book1.author, "Chand Miyan");
strcpy( Book1.subject, "C++ Programming");
Book1.book_id = 6495407;
// book 2 specification
strcpy( Book2.title, "Telecom Billing");
strcpy( Book2.author, "Yakit Singha");
strcpy( Book2.subject, "Telecom");
Book2.book_id = 6495700;
return 0;
}
When the above code is compiled and executed, it produces the following result −
Book 1 title : Learn C++ Programming
Book 1 author : Chand Miyan
Book 1 subject : C++ Programming
Book 1 id : 6495407
Book 2 title : Telecom Billing
Book 2 author : Yakit Singha
Book 2 subject : Telecom
Book 2 id : 6495700
int main() {
struct Books Book1; // Declare Book1 of type Book
struct Books Book2; // Declare Book2 of type Book
// book 1 specification
strcpy( Book1.title, "Learn C++ Programming");
strcpy( Book1.author, "Chand Miyan");
strcpy( Book1.subject, "C++ Programming");
Book1.book_id = 6495407;
// book 2 specification
strcpy( Book2.title, "Telecom Billing");
strcpy( Book2.author, "Yakit Singha");
strcpy( Book2.subject, "Telecom");
Book2.book_id = 6495700;
return 0;
}
void printBook( struct Books book ) {
cout << "Book title : " << book.title <<endl;
cout << "Book author : " << book.author <<endl;
cout << "Book subject : " << book.subject <<endl;
cout << "Book id : " << book.book_id <<endl;
}
When the above code is compiled and executed, it produces the following result −
Book title : Learn C++ Programming
Book author : Chand Miyan
Book subject : C++ Programming
Book id : 6495407
Book title : Telecom Billing
Book author : Yakit Singha
Book subject : Telecom
Book id : 6495700
Pointers to Structures
You can define pointers to structures in very similar way as you define pointer to
any other variable as follows −
struct Books *struct_pointer;
Now, you can store the address of a structure variable in the above defined pointer
variable. To find the address of a structure variable, place the & operator before the
structure's name as follows −
struct_pointer = &Book1;
To access the members of a structure using a pointer to that structure, you must
use the -> operator as follows −
struct_pointer->title;
Let us re-write above example using structure pointer, hope this will be easy for you
to understand the concept −
#include <iostream.h>
#include <string.h>
struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
};
int main() {
struct Books Book1; // Declare Book1 of type Book
struct Books Book2; // Declare Book2 of type Book
// Book 1 specification
strcpy( Book1.title, "Learn C++ Programming");
strcpy( Book1.author, "Chand Miyan");
strcpy( Book1.subject, "C++ Programming");
Book1.book_id = 6495407;
// Book 2 specification
strcpy( Book2.title, "Telecom Billing");
strcpy( Book2.author, "Yakit Singha");
strcpy( Book2.subject, "Telecom");
Book2.book_id = 6495700;
return 0;
}
// This function accept pointer to structure as parameter.
void printBook( struct Books *book ) {
cout << "Book title : " << book->title <<endl;
cout << "Book author : " << book->author <<endl;
cout << "Book subject : " << book->subject <<endl;
cout << "Book id : " << book->book_id <<endl;
}
When the above code is compiled and executed, it produces the following result −
Book title : Learn C++ Programming
Book author : Chand Miyan
Book subject : C++ Programming
Book id : 6495407
Book title : Telecom Billing
Book author : Yakit Singha
Book subject : Telecom
Book id : 6495700
Record - a linear, direct-access data structure with heterogeneous components.
See taxonomy.
Field or member - component of the record; each field has its own type
FieldName - the identifier used to refer to the field. The identifier only need to be
unique within the struct. It will not be in conflict with names used elsewhere or in
other structs.
Example:
Student (idnumber, name, status, credits, gpa)
enum StatusType {FULLTIME, PARTTIME, NONDEGREE, GRAD}
struct StudentType {
int idNumber;
char name[30];
StatusType status;
float credits;
float gpa;
};
StudentType student1;
StudentType student2;
Dot operator
The dot (.) operator is used to select members from a record (struct).
struct {
.....
} student1, student2; //no way to later make a new instance
This is an important feature. Compare to the fact that you cannot assign whole
arrays or strings by themselves. You must copy an array element by element, a
string using the strcpy( ) function.
student1 = student2; //OK
Fieldname Issues
The fieldnames are local to the struct.
The same member name can be used in other structs.
Every member name reference is always associated with the record or instance
name.
Membership
Any structure can be a member of a struct
struct NameType {
char first[15];
char middleInit;
char last[15];
};
struct StudentType {
NameType name;
int idNum;
float credits;
float gpa;
};
StudentType student1,student2;
student1.name.last;
student2.name.first[0];
Type compatibility
Two struct instances are compatible only if their types are identical or are
renamings of the same type.