Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Data Structure and Algorithms

Download as pdf or txt
Download as pdf or txt
You are on page 1of 42

Data Structures and

Algorithms - Arrays
Data Structures and Algorithms - Arrays
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.
Array Representation – cont’d
• 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 27.
Basic Operations
Following are the basic operations supported by an array.
• Traverse − print all the array elements one by one.
• Insertion − Adds an element at the given index.
• Deletion − Deletes an element at the given index.
• Search − Searches an element using the given index or by the value.
• Update − Updates an element at the given index.
Example:
• Find the address for LA [6].
• Each element of the array occupy 1 byte
LOC(LA[K]) = Base(LA) + w(K – lower
bound).
• Solution:
LOC(LA[6]) = 200 + 1(6 – 0) = 206
Operations on Arrays
The operation performed on any linear structure, where it can be an array or
linked list, include the following
1. Traversal: processing each element in the list exactly once.
2. Insertion: adding new element to the list.
3. Deletion: removing an element from the list.
4. Searching: finding location of the element with a given value or key.
5. Sorting: Arranging elements in some type of order.
6. Merging: Combining two lists into a single list.
Traversing
• Let A be a collection of data elements stored in the memory of the
computer.
• Suppose we want to print the content of each element of A or count the
number of elements of A with a given property.
• This can be accomplished by traversing A, that is, by accessing and
processing (frequently called visiting) each element of A exactly once.
The following algorithm traverses a linear array:

Algorithm: (Traversing a linear array.)


Here, A is a linear array with lower bound LB and upper bound UB. This
algorithm traverses A applying an operation PROCESS to each element of
A.
Step 1: [Initialize counter] Set I:= LB.
Step 2: Repeat steps 3 and 4 while I<= UB:
Step 3: [Visit element.] Apply PROCESS to A.
Step 4: [Increase counter.] Set I:= I+1.
[End of step 2 loop.]
Step 5: Exit.
C++ Single Dimensional Array
An example of C++ array, where we are going to create, initialize and traverse array.
#include <iostream>
using namespace std;
int main()
{
int arr[5]={10, 0, 20, 0, 30}; //creating and initializing array
//traversing array
for (int i = 0; i < 5; i++)
{
cout<<arr[i]<<"\n";
}
} array
Output:/p>
10
0
20
0
30
//Program to read five numbers, find their sum, and print the
numbers in reverse order.
#include <iostream> cout << endl;
using namespace std; cout << "The sum of the numbers is: " << sum <<
endl;
int main()
{ cout << "The numbers in reverse order are: ";
int A[5]; //Declare an array item of five components //Print the numbers in reverse order.
for (i = 4; i >= 0; i--)
int sum;
int i; cout << A[i] << " ";
cout << "Enter five numbers: "; cout << endl;
return 0;
sum = 0;
for (i = 0; i < 5; i++) }
{
cin >> A[i];
sum = sum + A[i]; arrayreverse
}
Sample Run: In this sample run, the user
input is shaded.
Enter five numbers: 12 76 34 52 89
The sum of the numbers is: 263
The numbers in reverse order are: 89 52 34 76 12
Array Index
C++ Passing Array to Function
• In C++, to reuse the array logic, we can create function.
• To pass array to function in C++, we need to provide only array name.
functionname(arrayname); //passing array to function

• C++ Passing Array to Function Example: print array elements


An Example of C++ function which prints the
array elements.
#include <iostream> void printArray(int arr[5])
using namespace std; {
void printArray(int arr[5]); cout << "Printing array elements:"<< endl;
int main() for (int i = 0; i < 5; i++)
{ {
int arr1[5] = { 10, 20, 30, 40, 50 }; cout<<arr[i]<<"\n";
int arr2[5] = { 5, 15, 25, 35, 45 }; }
printArray(arr1); //passing array to functio }
n
printArray(arr2);
}
Output:
Printing array elements:
10
20
30
40
50
Printing array elements:
5
15
25
35
45
C++ Passing Array to Function Example: Print
minimum number
An example of C++ array which prints minimum void printMin(int arr[5])
number in an array using function. {
#include <iostream>
int min = arr[0];
using namespace std; for (int i = 0; i <5; i++)
void printMin(int arr[5]); {
int main()
if (min > arr[i])
{ {
int arr1[5] = { 30, 10, 20, 40, 50 }; min = arr[i];
int arr2[5] = { 5, 15, 25, 35, 45 };
}
printMin(arr1);//passing array to function }
printMin(arr2); cout<< "Minimum element is: "<< min <<"\n";
}
}
Output:
Minimum element is: 10
Minimum element is: 5
C++ Passing Array to Function Example: Print
maximum number
//An example of C++ array which prints maximum void printMax(int arr[5])
number in an array using function. {
#include <iostream>
int max = arr[0];
using namespace std; for (int i = 0; i < 5; i++)
void printMax(int arr[5]); {
int main()
if (max < arr[i])
{ {
int arr1[5] = { 25, 10, 54, 15, 40 }; max = arr[i];
int arr2[5] = { 12, 23, 44, 67, 54 };
}
printMax(arr1); //Passing array to function }
printMax(arr2); cout<< "Maximum element is: "<< max <<"\n";
}
}
Output:
Maximum element is: 54
Maximum element is: 67
C++ Multidimensional Arrays
• The multidimensional array is also known as rectangular arrays in C++.
It can be two dimensional or three dimensional.
• The data is stored in tabular form (row ∗ column) which is also known
as matrix.
C++ Multidimensional Array Example
//An example of multidimensional array in C++ which declares, //traversal
initializes and traverse two dimensional arrays. for(int i = 0; i < 3; ++i)
#include <iostream>
{
using namespace std; for(int j = 0; j < 3; ++j)
int main() {
{
cout<< test[i][j]<<" ";
int test[3][3]; //declaration of 2D array }
test[0][0]=5; //initialization cout<<"\n"; //new line at each row
test[0][1]=10;
}
test[0][2] = 23; return 0;
test[1][1]=15; }
test[1][2]=20;
test[2][0]=30;
test[2][2]=10;
Output:
5 10 0
0 15 20
30 0 10
C++ Multidimensional Array Example:
Declaration and initialization at same time
//An example of multidimensional array which //traversal
initializes array at the time of declaration. for(int i = 0; i < 3; ++i)
#include <iostream> {
using namespace std; for(int j = 0; j < 3; ++j)
int main() {
{ cout<< test[i][j]<<" ";
int test[3][3] = }
{ cout<<"\n"; //new line at each row
{2, 5, 5}, }
{4, 0, 3}, return 0;
{9, 1, 8} }; //declaration and initialization }
Output:
255
403
918
Data Types and Default values
• In C++, when an array is Data Type Default Value

initialized with size, then it bool false

assigns defaults values to its char 0

elements in following order. int 0

float 0.0

double 0.0f

void
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 −
Insertion
• Let A be a collection of data elements in the memory of the
computer.
• “Inserting” refers to the operation of adding another element to the
collection A, Inserting an element at the ‘end’ of a linear array can be
easily done.
• On the other hand, suppose we need to insert an element in the
middle of the array.
• Then on the average, half of the elements must be moved downward
to new locations to accommodate the new element and keep an
order of the order of the other elements.
Algorithm: (Inserting into a linear array.)
INSERT (A, N, K, ITEM).
Here, A is a linear array with N elements and K is a positive integer such that K <= N.
This algorithm inserts an element ITEM into the Kth position in A.
Step 1: [Initialize counter.] Set I:= N.
Step 2: Repeat steps 3 and 4 while I >= K:
Step 3: [Move element downward.] Set A[I+1] := A[I].
Step 4: [Decrease counter.] I:= I-1.
[End of step 2 loop.]
Step 5: [Insert element.] Set A[K] := ITEM.
Step 6: [Reset N.] Set N:= N+1.
Step 7: Exit.
Algorithm
To sort an array of size n in ascending order:
1: Iterate from arr[1] to arr[n] over the array.
2: Compare the current element (key) to its predecessor.
3: If the key element is smaller than its predecessor, compare it to the
elements before. Move the greater elements one position up to make
space for the swapped element.
Example:
Another Example:
12, 11, 13, 5, 6
Let us loop for i = 1 (second element of the array) to 4 (last element of the
array)
i = 1. Since 11 is smaller than 12, move 12 and insert 11 before 12
11, 12, 13, 5, 6
i = 2. 13 will remain at its position as all elements in A[0..I-1] are smaller than
13
11, 12, 13, 5, 6
i = 3. 5 will move to the beginning and all other elements from 11 to 13 will
move one position ahead of their current position.
5, 11, 12, 13, 6
i = 4. 6 will move to position after 5, and elements from 11 to 13 will move one
position ahead of their current position.
5, 6, 11, 12, 13
Insertion Operation - Algorithm
Example: Following is the implementation of n = n + 1;
the above algorithm: insertarray1.cpp while( j >= k) {
#include <iostream> LA[j+1] = LA[j];
using namespace std; j = j - 1;
}
int main() {
LA[k] = item;
int LA[] = {1,3,5,7,8}; cout<<("The array elements after
int item = 10, k = 3, n = 5; insertion :\n");
for(i = 0; i<n; i++) {
int i = 0, j = n;
cout<<(i, LA[i]) << endl;
cout<<("The original array elements are :\n"); }
for(i = 0; i<n; i++) { }
cout<<(i, LA[i]) <<endl;
}
• When we compile and execute the above program, it produces the
following result
Deletion
• Let A be a collection of data elements in the memory of the
computer. “Deleting” refers to the operation of removing one of the
elements from A.
• Deleting an element at the ‘end’ of an array presents no difficulties,
but deleting an element somewhere in the middle of the array would
require that each subsequent element is moved one location upward
in order to ‘fill up’ the array.
Deletion Operation
Deletion refers to removing an existing element from the array and re-organizing all
elements of an array.
Algorithm
Consider LA is a linear array with N elements and K is a positive integer such that
K<=N. Following is the algorithm to delete an element available at the Kth position
of LA.
1. Start
2. Set J = K
3. Repeat steps 4 and 5 while J < N
4. Set LA[J] = LA[J + 1]
5. Set J = J+1
6. Set N = N-1
7. Stop
Example – Delete array
Following is the implementation of the above while( j < n) {
algorithm − deletearray1.cpp LA[j-1] = LA[j];
#include <iostream> j = j + 1;
using namespace std; }
int main() { n = n -1;
int LA[] = {1,3,5,7,8}; cout<<("The array elements after deletion
int k = 3, n = 5; :\n");
int i, j; for(i = 0; i<n; i++) {
cout<<("The original array elements are :\n"); cout<<(i, LA[i])<<endl;
for(i = 0; i<n; i++) { }
cout<<(i, LA[i]) <<endl; }
}
j = k;
Search Operation
• You can perform a search for an array element based on its value or its index.
Algorithm
Consider LA is a linear array with N elements and K is a positive integer such that
K<=N. Following is the algorithm to find an element with a value of ITEM using
sequential search.
1. Start
2. Set J = 0
3. Repeat steps 4 and 5 while J < N
4. IF LA[J] is equal ITEM THEN GOTO STEP 6
5. Set J = J +1
6. PRINT J, ITEM
7. Stop
Example – Search Array
Following is the implementation of the above while( j < n){
algorithm searcharray.cpp if( LA[j] == item ) {
using namespace std; break;
int main() { }
int LA[] = {1,3,5,7,8}; j = j + 1;
int item = 5, n = 5; }
int i = 0, j = 0; cout<<"The array elements after serached
cout<<("The original array elements are :\n";
:\n"); cout<<(item, j+1)<<endl;
for(i = 0; i<n; i++) { }
cout<<(i, LA[i])<<endl;
}
Update Operation
• Update operation refers to updating an existing element from the
array at a given index.
• Algorithm
• Consider LA is a linear array with N elements and K is a positive
integer such that K<=N. Following is the algorithm to update an
element available at the Kth position of LA.
1. Start
2. Set LA[K-1] = ITEM
3. Stop
Example: implementation of the above algorithm
#include <iostream> larrayupdate1.cpp
using namespace std;
int main() {
int LA[] = {1,3,5,7,8};
int k = 3, n = 5, item = 10;
int i, j;
cout << "The original array elements are :\n";
for(i = 0; i<n; i++) {
cout << LA[i] << endl;
}
LA[k-1] = item;
cout << "The array elements after updation :\n";
for(i = 0; i<n; i++) {
cout << LA[i] << endl;
}
}
Thank You.

You might also like