SlideShare a Scribd company logo
Page 1 of 14

Array
Areas Covered on:

1- D ARRAY
. Definition of 1-D
array.

Implementation of 1-D
array

Basic operations of 1-D
array

Insertion & Deletion

. Searching

Sorting

. Merging

1-D Array Definations:
One dimensional array comprise of finite homogeneous elements represented as:
Array name [Lower bound L, Upper bound U] ranges from L through U.

To calculate array size (length) =U-L+1
Ex: Ar [-9, 15]
Size=15-(-9) +1=23

Implementation of 1-D array:

It is done to calculate address of any element in an array.
Address of element with subscript I=Base address +ES (I-L)
Where ES is size of an array element
L is the lower bound of the array.

Prepared By Sumit Kumar Gupta, PGT Computer Science
Page 2 of 14

Basic operations of 1-D array:--1. Insertion & Deletion
2. Searching
3. Sorting
4. Merging

Insertion: placing of new element within the existing array.
Insertion is done in two ways:
i) If the array is unordered, placing the new element at the end of the array.
ii)if the array is sorted then new element is added at appropriate position.

Algorithm:
1.ctr=L
2.If LST=U then
{
Print “Overflow:”
Exit from program
}
3. if AR[ctr]>ITEM then
Pos=1
Else
{
4. Repeat steps 5 and 6 until ctr>=U
5. if AR[ctr]<=ITEM and ITEM<=AR[ctr+1] then
{ Pos=ctr+1
Break
}
6. ctr=ctr+1
/*end of repeat here*/
7. if ctr=U then
Pos=U+1
}
/*end of if step 3 */
/* shift the element to create space*/
8. ctr=U
9.while ctr>=pos perform steps 10 through 11
10.AR[ctr+1]=AR[ctr]

Prepared By Sumit Kumar Gupta, PGT Computer Science
Page 3 of 14
11.ctr=ctr=ctr-1
}
12. AR[pos]=ITEM
13. END

Using Function:
int FindPos(int AR[],int size,int item) /*to determine the position for element
{
int pos;
if(item<AR[0]) pos=0;
else
{
for(int i=0;i<size-1;i++)
{
if(AR[i]<=item && item <AR[i+1]
{
Pos=i+1;
Break;
}
if(i==size-1) pos=size;
}
return pos;
}
Deletion:
To delete an element from existing array.
Algorithm:
/*considering that Item’s search in array AR is successful at location pos*/
Two cases arises:
Case1: Shifting Upward or left side
1. ctr=pos
2. Repeat steps 3 and 4 until ctr>=U
3. AR [ctr] =AR [ctr-1]
4. ctr=ctr+1

Prepared By Sumit Kumar Gupta, PGT Computer Science
Page 4 of 14
/*end of repeat*/
Case II: shifting downwards (or in right side)
1. Ctr=pos
2. Repeat steps 3 and 4 until Ctr<=L
3.AR[ctr]=AR[ctr-1]
4.ctr=ctr-1
/*End of Repeat*/
Searching:

Linear search:
Linear search method is used to scan the array in a sequential
manner.Under this method the whole array is searched one by one until the
matching element is obtained .
Note: Linear search is done in Unordered array.
Algorithm:
/*Initialise counter by assigning lower bound value of the array*/
Step1:Set ctr=L

(Lower bound=0 in c++)

/*Now search for the ITEM*/
Step2: Repeat steps 3 through 4 until ctr>U //Upper Bound(U) is size-1
Step3: if AR [ctr]==ITEM then
{
Print “search Successful”
Print ctr,”is the location of”,ITEM
Break
}
Step 4: ctr=ctr+1
/*End of repeat*/
Step 5 if ctr>U then
Print “search Unsuccessful!”
Step 6 END

Using Function:
Int LSearch(int AR[],int size,int item)
{
For(int i=0;i<size;i++)
{

Prepared By Sumit Kumar Gupta, PGT Computer Science
Page 5 of 14
If(AR[i]==item)
return i;
}
return -1;
}

Binary search:
Steps:To search for ITEM in sorted array (in ascending order)
1. ITEM is compared with middle element of the segment(i.e,in the entire
array for the first time).
2.If the ITEM is more than the middle element ,latter part of the segment
becomes new segment to be scanned.
3.The same process is repeated for the new segment(s) until the item is
found(search successful) or the segment is reduced to the single element and
the ITEM is not found(search Unsuccessful).
Condition: Array should be in sorted manner
Using Function:
int Bsearch(int AR[10], int I, int N)
{
int beg=0, last = N-1,Mid;
While(beg<=last)
{
Mid =(beg+last)/2;
If (AR[Mid]==I)
Return 1;
Else if (I > AR[Mid])
Beg=Mid+1;
Else
Last=Mid-1;
}
return 0;
}

Sorting:
Selection Sorting:
Steps:

Prepared By Sumit Kumar Gupta, PGT Computer Science
Page 6 of 14
Pass-1 Find the location LOC of the smallest in the list of n elements.
a[1],a[2],……..a[n],then interchange a[loc]with a[1].
Pass-2 Find the location LOC and then interchanged a [LOC] and a [2].since
a[1]<=a[2]
Pass-3 Find the location LOC of the smallest in the sublist of n-2 elements.
a [3],a[4],……a[n], and then interchanged a[LOC] and a[3].Then
a[1],a[2]….a[3] is stored, since a[2]<=a[3]
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Pass N-1: Find the location LOC of the smallest of the elements a[n-],a[n] and
interchanged a[LOC] and a[n-1].Then:
a [1],a[2]….a[n] is strored, since a[n-1]<=a[n]
Thus a is sorted after n-1 passes
Algorithm:
1. small=AR[L]
2. For i=L to U do
{
3.
small=AR[i]
4.
for J=I to U do
{
5.
If AR[j]<small then
6.
{
Small==AR[j]
7.
Pos=j
}
j=j+1;
}

//In c++ ,0 to size-1

/*end of inner loop*/

/*swap the smallest element with ith element */
8. temp=AR[i]
9. AR[i]=small
10. AR[pos]=temp
}
11. END

Prepared By Sumit Kumar Gupta, PGT Computer Science
Page 7 of 14

Using Function :
Void SelSort(int AR[],int size)
{
int small, pos,tmp;
for(int i=0;i<size;i++)
{
small=AR[i];
for(int j=i+1;j<size;j++)
{
if(AR[j]<small)
{
small=AR[j];
pos=j;
}
}
tmp=AR[i];
AR[i]=AR[pos];
AR[pos]=tmp;
cout<<”n Array after pass –“<<i+1<<”—is :”;
for(j=0;j<size;j++)
cout<<AR[j]<<””;
}
}

Bubble Sort

The basic idea of bubble sort is to compare two adjoining values and exchange them
if they are not in proper order.
Algorithm:
1. For I=L to U
2. {
For j=to [(U-1)-I]
{

Prepared By Sumit Kumar Gupta, PGT Computer Science
Page 8 of 14
3.

If AR[j]>AR[j+1] then
{
temp=AR[j]
AR[j]=AR[j+1]
AR[j+1]=temp
}

4.
5.
6.
}
}
7.

END

Using Function

Void BubbleSort(int AR[],int size)
{
int tmp,ctr=0;
for(int i=0;i<size;i++)
{
for (int j=0;j<(size-1)-i;j++)
{
if(AR[j]<AR[j+1])
{
tmp=AR[j];
AR[j]=Ar[j+1];
AR[j+1]=tmp;
}
}
cout<<”Array after iteration—“<<++ctr<<”--: “;
for(int k=0;k<size;k++)
cout<<AR[k]<<””;
cout<<endl
}
}

Insertion sorting:
Condition: Introduce a sentinel element A [0] = - ∞ (or a very small number)
An insertion sort is one that sorts a set of values by inserting values into an
existing sorted file.

Prepared By Sumit Kumar Gupta, PGT Computer Science
Page 9 of 14
The insertion sort algorithm scans array a from a[1] to a[n], inserting each
element
A[k] into its proper position on the previously sorted subarray a [1],a [2]...a [k1].

Using Function:
Void InsSort (int AR [], int size)
{
int tmp,j;
AR [0] =INT_MIN;
for (int i=1;i<=size;i++)
{
tmp=AR[i];
j=i-1;
while(tmp<AR[j])
{
AR[j+1]=AR[j];
j--;
}
AR[j+1]=tmp;
cout<<”Array after iteration—“<<++ctr<<”--: “;
for (int k=0;k<size;k++)
cout<<AR[k]<<””;
cout<<endl;
}
}

Merging:
Merging means combining elements of two arrays to form a new array.
Merging in array
/* Merging of two array A and B where A is in ascending order ,B is in ascending
order and resultant array C will be in Ascending
ctr A=L1
ctr B=L2
ctr C=L3
while (ctr A<=U1) &&( ctr B<=U2)
{
If(A[ctr A]<=B[ctr B]) then

Prepared By Sumit Kumar Gupta, PGT Computer Science
Page 10 of 14
{
C[ctr C]=A[ctr A]
ctr C=ctr C + 1
ctr A=ctr A+1
}
else
{
C[ctr C]=B[ctr B]
ctr C=ctr C+1
ctr B=ctr B+1
}/*end of while loop
If(ctr A >U1) then
{
While(ctr B <=U2)
{
C[ctrC]=B[ctr B]
ctrC=ctrC+1
ctr B=ctr B+1
}
}
If(ctr B>U2) then
{
While (ctr A<=U1)
{
C[ctr C]=A[ctr A]
ctr C=ctr C+1
ctr A=ctr A+1
}
}
There are some other cases are also possible .These cases are taken place in
following situations:
1. When array A[n] is in Acsending order then its control variable ,say ctr A
,should be initialized with array’s lower bound ,which is 0(zero).And the test
condition will be ctr<n.
2. When an array ,say A[n] ,is in descending order,then its control variable ,say
ctr A ,should be initialized with array’s upper bound,which is n-1.

Prepared By Sumit Kumar Gupta, PGT Computer Science
Page 11 of 14
Assuming length of array A is M and Length of array B is N-1 . Thus array A has
elements A[0] to A[N-1] and B has elements B[0] to B[N-1] .let the resultant array be
C with length 10.
CtrB=n-1 , ctrA=0 , ctrC=0
while (ctrC<5) do
{
C[ctrC]=A[ctrA]
ctrC=ctrC+1
ctrA=ctrA+1
}
while (ctrC<10) do
{ C[ctrC]=B[ctrB]
ctrC=ctrC+1
ctrB=ctrB-1
}
ctrC=0
while(ctrC<10) do
{
print C[ctrC]
ctrC= ctrC+1
}
END

Solved Examples:
Q.1 What do you understand by Data Structure. Describe about the types of data
structure
Ans A data Structure is a named group of data of different data types which can be
processed as single unit.
There are two types of data structure
a. Simple :- i. Array ii. Structure
b. Complex
i. Linear :- i.Stack ii. Queue iii. Linked-list
ii. Non-Linear : Tree
Q.2What will be the address of 5th element in a floating point array implemented in
C++?The array is specified as amount[16].the base address of the array is 1058.
Ans) Standard size of floating-point array=4 bytes
5th element in the array Amount is specified as Amount[4] as the index numbers
in c++ starts from 0.
Address of Amount[4]=base address +es(I-L)
L=0

Prepared By Sumit Kumar Gupta, PGT Computer Science
Page 12 of 14
Es=4
Base Address=1058
Putting all these values,
Address of Amount[4]=1058+4(4-0)=1074
Q.3 Suppose a one dimentional Array AR containing integers is arranged in
ascending order .Write a user defined function in C++ to search for one integer
from AR with the help of Binary Search Method , returning an integer 0 to show
absence of the number and 1 to show the presence of the number in the array. The
function should have three parameters (1. an array AR 2. the number to be
searched 3. the number of elements N)
Ans. Int Bsearch(int AR[10], int I, int N)
{
int beg=0, last = N-1,Mid;
While(beg<=last)
{
Mid =(beg+last)/2;
If (AR[Mid]==I)
Return 1;
Else if (I > AR[Mid])
Beg=Mid+1;
Else
Last=Mid-1;
}
return 0;
}

Practice also For Descending order
Q.4 Write a function in C++ which accepts an integer array and its size as
arguments and exchange the values of first half side element with the second half
elements of the array. Example if an array of 10 elements has initial content
12,15,45,23,34,43,77,46,35,47
The resultant array should be like this 43,77,46,35,47,12,15,45,23,34
Ans void swap( int A[ ] ,int size)
{
int I,j,temp,mid=size/2;
if (size %2 = = 0)
j=mid ;
else
j=mid+1;
for(i=0;i<mid;i++,j++)
{
temp= A[i];

Prepared By Sumit Kumar Gupta, PGT Computer Science
Page 13 of 14
A[i]=A[j];
A[j]=temp;
}
}
5. Write an Algorithm for Selection Sort .
Ans :
1. small=AR[L]
2. for i= L to U loop
3. { small = AR[i]
4. for j = I to U
do
5. { if AR[j] < small then
6. { small = AR[j]
7. pos = j
}
8. j = j + 1
}
9. temp = AR[i]
10. AR[i] = small
11. AR[pos] = temp
}
12. end
Q.6 An algorithm requires two stacks of size M and N that are to be
maintained in the memory .Illustrate with an example how will you adjust two
stacks in one dimensional array with M+N memory locations so that the overflow
condition is minimized .
Ans . let us say that the stack A is with size M and Stack B with size N
If the stack A is stored in locations 0 to M-1 and the stack B is stored in locations
M to M+N-1 ,the separate areas for the two are ensured .in the beginning the tops of the
stacks are at opposite ends . when Top A reaches at M-1 , any further insertion will lead
to overflow in stack A and when Top B reaches at M. any further insertion in stack B will
lead to overflow.
Q.7 Given two arrays A and B ,copy last five element of B after first five element of
A to create another array C. Assume length of A and B is greater than 5.(Merge
Sort)
Ans Assuming length of array A is M and Length of array B is N-1 . thus array A has
elements A[0] to A[N-1] and B has elements B[0] to B[N-1] .let the resultant array be C
with length 10.
ctrB=n-1 , ctrA=0 , ctrC=0
while (ctrC<5) do
{ C[ctrC]=A[ctrA]
ctrC=ctrC+1
ctrA=ctrA+1
}
while (ctrC<10) do
{ C[ctrC]=B[ctrB]
ctrC=ctrC+1

Prepared By Sumit Kumar Gupta, PGT Computer Science
Page 14 of 14
ctrB=ctrB-1
}
ctrC=0
while(ctrC<10) do
{
print C[ctrC]
ctrC= ctrC+1
}
END

|

Prepared By Sumit Kumar Gupta, PGT Computer Science

More Related Content

What's hot

Strassen's matrix multiplication
Strassen's matrix multiplicationStrassen's matrix multiplication
Strassen's matrix multiplication
Megha V
 
Encapsulation of operations, methods & persistence
Encapsulation of operations, methods & persistenceEncapsulation of operations, methods & persistence
Encapsulation of operations, methods & persistence
Prem Lamsal
 
PL/SQL TRIGGERS
PL/SQL TRIGGERSPL/SQL TRIGGERS
PL/SQL TRIGGERS
Lakshman Basnet
 
STRUCTURE OF SQL QUERIES
STRUCTURE OF SQL QUERIESSTRUCTURE OF SQL QUERIES
STRUCTURE OF SQL QUERIES
VENNILAV6
 
Data Structure and Algorithms Merge Sort
Data Structure and Algorithms Merge SortData Structure and Algorithms Merge Sort
Data Structure and Algorithms Merge Sort
ManishPrajapati78
 
Heap Tree.pdf
Heap Tree.pdfHeap Tree.pdf
Heap Tree.pdf
manahilzulfiqar6
 
Primary Key & Foreign Key part10
Primary Key & Foreign Key part10Primary Key & Foreign Key part10
Primary Key & Foreign Key part10
DrMohammed Qassim
 
Sequence Diagram
Sequence DiagramSequence Diagram
Types Of Join In Sql Server - Join With Example In Sql Server
Types Of Join In Sql Server - Join With Example In Sql ServerTypes Of Join In Sql Server - Join With Example In Sql Server
Types Of Join In Sql Server - Join With Example In Sql Server
programmings guru
 
Group By, Having Clause and Order By clause
Group By, Having Clause and Order By clause Group By, Having Clause and Order By clause
Group By, Having Clause and Order By clause
Deepam Aggarwal
 
Quick sort
Quick sortQuick sort
Quick sort
Dhruv Sabalpara
 
Relational Data Model Introduction
Relational Data Model IntroductionRelational Data Model Introduction
Relational Data Model Introduction
Nishant Munjal
 
Dsc++ unit 3 notes
Dsc++ unit 3 notesDsc++ unit 3 notes
Dsc++ unit 3 notes
Guru Nanak Institute Of Tech
 
Trees
TreesTrees
Activity diagrams
Activity diagramsActivity diagrams
Activity diagrams
Jalaxy Jahury
 
One Dimensional Array
One Dimensional Array One Dimensional Array
One Dimensional Array
dincyjain
 
SQL Data Manipulation
SQL Data ManipulationSQL Data Manipulation
SQL Data Manipulation
khalid alkhafagi
 
Dbms Notes Lecture 9 : Specialization, Generalization and Aggregation
Dbms Notes Lecture 9 : Specialization, Generalization and AggregationDbms Notes Lecture 9 : Specialization, Generalization and Aggregation
Dbms Notes Lecture 9 : Specialization, Generalization and Aggregation
BIT Durg
 
Non- Deterministic Algorithms
Non- Deterministic AlgorithmsNon- Deterministic Algorithms
Non- Deterministic Algorithms
Dipankar Boruah
 
joins in database
 joins in database joins in database
joins in database
Sultan Arshad
 

What's hot (20)

Strassen's matrix multiplication
Strassen's matrix multiplicationStrassen's matrix multiplication
Strassen's matrix multiplication
 
Encapsulation of operations, methods & persistence
Encapsulation of operations, methods & persistenceEncapsulation of operations, methods & persistence
Encapsulation of operations, methods & persistence
 
PL/SQL TRIGGERS
PL/SQL TRIGGERSPL/SQL TRIGGERS
PL/SQL TRIGGERS
 
STRUCTURE OF SQL QUERIES
STRUCTURE OF SQL QUERIESSTRUCTURE OF SQL QUERIES
STRUCTURE OF SQL QUERIES
 
Data Structure and Algorithms Merge Sort
Data Structure and Algorithms Merge SortData Structure and Algorithms Merge Sort
Data Structure and Algorithms Merge Sort
 
Heap Tree.pdf
Heap Tree.pdfHeap Tree.pdf
Heap Tree.pdf
 
Primary Key & Foreign Key part10
Primary Key & Foreign Key part10Primary Key & Foreign Key part10
Primary Key & Foreign Key part10
 
Sequence Diagram
Sequence DiagramSequence Diagram
Sequence Diagram
 
Types Of Join In Sql Server - Join With Example In Sql Server
Types Of Join In Sql Server - Join With Example In Sql ServerTypes Of Join In Sql Server - Join With Example In Sql Server
Types Of Join In Sql Server - Join With Example In Sql Server
 
Group By, Having Clause and Order By clause
Group By, Having Clause and Order By clause Group By, Having Clause and Order By clause
Group By, Having Clause and Order By clause
 
Quick sort
Quick sortQuick sort
Quick sort
 
Relational Data Model Introduction
Relational Data Model IntroductionRelational Data Model Introduction
Relational Data Model Introduction
 
Dsc++ unit 3 notes
Dsc++ unit 3 notesDsc++ unit 3 notes
Dsc++ unit 3 notes
 
Trees
TreesTrees
Trees
 
Activity diagrams
Activity diagramsActivity diagrams
Activity diagrams
 
One Dimensional Array
One Dimensional Array One Dimensional Array
One Dimensional Array
 
SQL Data Manipulation
SQL Data ManipulationSQL Data Manipulation
SQL Data Manipulation
 
Dbms Notes Lecture 9 : Specialization, Generalization and Aggregation
Dbms Notes Lecture 9 : Specialization, Generalization and AggregationDbms Notes Lecture 9 : Specialization, Generalization and Aggregation
Dbms Notes Lecture 9 : Specialization, Generalization and Aggregation
 
Non- Deterministic Algorithms
Non- Deterministic AlgorithmsNon- Deterministic Algorithms
Non- Deterministic Algorithms
 
joins in database
 joins in database joins in database
joins in database
 

Viewers also liked

1 D Arrays in C++
1 D Arrays in C++1 D Arrays in C++
1 D Arrays in C++
poonam.rwalia
 
1-D array
1-D array1-D array
Strings in C
Strings in CStrings in C
Strings in C
Kamal Acharya
 
String in c
String in cString in c
String in c
Suneel Dogra
 
Arrays In C++
Arrays In C++Arrays In C++
Arrays In C++
Awais Alam
 
Array in C
Array in CArray in C
Array in C
Kamal Acharya
 
Arrays
ArraysArrays
Array in c language
Array in c languageArray in c language
Array in c language
home
 

Viewers also liked (8)

1 D Arrays in C++
1 D Arrays in C++1 D Arrays in C++
1 D Arrays in C++
 
1-D array
1-D array1-D array
1-D array
 
Strings in C
Strings in CStrings in C
Strings in C
 
String in c
String in cString in c
String in c
 
Arrays In C++
Arrays In C++Arrays In C++
Arrays In C++
 
Array in C
Array in CArray in C
Array in C
 
Arrays
ArraysArrays
Arrays
 
Array in c language
Array in c languageArray in c language
Array in c language
 

Similar to 1D Array

DAA-Divide and Conquer methodology, DAA 2024
DAA-Divide and Conquer methodology, DAA 2024DAA-Divide and Conquer methodology, DAA 2024
DAA-Divide and Conquer methodology, DAA 2024
RUHULAMINHAZARIKA
 
DATA STRUCTURE CLASS 12 COMPUTER SCIENCE
DATA STRUCTURE CLASS 12 COMPUTER SCIENCEDATA STRUCTURE CLASS 12 COMPUTER SCIENCE
DATA STRUCTURE CLASS 12 COMPUTER SCIENCE
Dev Chauhan
 
data structure and algorithm Array.pptx btech 2nd year
data structure and algorithm  Array.pptx btech 2nd yeardata structure and algorithm  Array.pptx btech 2nd year
data structure and algorithm Array.pptx btech 2nd year
palhimanshi999
 
Data structure using c module 1
Data structure using c module 1Data structure using c module 1
Data structure using c module 1
smruti sarangi
 
sorting1.pptx
sorting1.pptxsorting1.pptx
sorting1.pptx
AJAYVISHALRP
 
ARRAY in python and c with examples .pptx
ARRAY  in python and c with examples .pptxARRAY  in python and c with examples .pptx
ARRAY in python and c with examples .pptx
abhishekmaurya102515
 
Array 31.8.2020 updated
Array 31.8.2020 updatedArray 31.8.2020 updated
Array 31.8.2020 updated
vrgokila
 
DATASTRUCTURES UNIT-1
DATASTRUCTURES UNIT-1DATASTRUCTURES UNIT-1
DATASTRUCTURES UNIT-1
Malikireddy Bramhananda Reddy
 
2-D array
2-D array2-D array
2D Array
2D Array2D Array
2D Array
Swarup Boro
 
Unit 7 sorting
Unit 7   sortingUnit 7   sorting
Unit 7 sorting
kalyanineve
 
Arrays in C.pptx
Arrays in C.pptxArrays in C.pptx
Arrays in C.pptx
HarsimranKaur362773
 
Data structure lecture 4
Data structure lecture 4Data structure lecture 4
Data structure lecture 4
Kumar
 
Daa chapter5
Daa chapter5Daa chapter5
Daa chapter5
B.Kirron Reddi
 
Sorting
SortingSorting
Array 2
Array 2Array 2
Array 2
Abbott
 
Sorting pnk
Sorting pnkSorting pnk
Sorting pnk
pinakspatel
 
Arrays
ArraysArrays
Arrays
Komal Singh
 
Merge sort
Merge sortMerge sort
Merge sort
Rojin Khadka
 
Introduction to Algorithms
Introduction to AlgorithmsIntroduction to Algorithms
Introduction to Algorithms
pppepito86
 

Similar to 1D Array (20)

DAA-Divide and Conquer methodology, DAA 2024
DAA-Divide and Conquer methodology, DAA 2024DAA-Divide and Conquer methodology, DAA 2024
DAA-Divide and Conquer methodology, DAA 2024
 
DATA STRUCTURE CLASS 12 COMPUTER SCIENCE
DATA STRUCTURE CLASS 12 COMPUTER SCIENCEDATA STRUCTURE CLASS 12 COMPUTER SCIENCE
DATA STRUCTURE CLASS 12 COMPUTER SCIENCE
 
data structure and algorithm Array.pptx btech 2nd year
data structure and algorithm  Array.pptx btech 2nd yeardata structure and algorithm  Array.pptx btech 2nd year
data structure and algorithm Array.pptx btech 2nd year
 
Data structure using c module 1
Data structure using c module 1Data structure using c module 1
Data structure using c module 1
 
sorting1.pptx
sorting1.pptxsorting1.pptx
sorting1.pptx
 
ARRAY in python and c with examples .pptx
ARRAY  in python and c with examples .pptxARRAY  in python and c with examples .pptx
ARRAY in python and c with examples .pptx
 
Array 31.8.2020 updated
Array 31.8.2020 updatedArray 31.8.2020 updated
Array 31.8.2020 updated
 
DATASTRUCTURES UNIT-1
DATASTRUCTURES UNIT-1DATASTRUCTURES UNIT-1
DATASTRUCTURES UNIT-1
 
2-D array
2-D array2-D array
2-D array
 
2D Array
2D Array2D Array
2D Array
 
Unit 7 sorting
Unit 7   sortingUnit 7   sorting
Unit 7 sorting
 
Arrays in C.pptx
Arrays in C.pptxArrays in C.pptx
Arrays in C.pptx
 
Data structure lecture 4
Data structure lecture 4Data structure lecture 4
Data structure lecture 4
 
Daa chapter5
Daa chapter5Daa chapter5
Daa chapter5
 
Sorting
SortingSorting
Sorting
 
Array 2
Array 2Array 2
Array 2
 
Sorting pnk
Sorting pnkSorting pnk
Sorting pnk
 
Arrays
ArraysArrays
Arrays
 
Merge sort
Merge sortMerge sort
Merge sort
 
Introduction to Algorithms
Introduction to AlgorithmsIntroduction to Algorithms
Introduction to Algorithms
 

More from Swarup Boro

Concatenation of two strings using class in c++
Concatenation of two strings using class in c++Concatenation of two strings using class in c++
Concatenation of two strings using class in c++
Swarup Boro
 
Program: Inheritance in Class - to find topper out of 10 students
Program: Inheritance in Class - to find topper out of 10 studentsProgram: Inheritance in Class - to find topper out of 10 students
Program: Inheritance in Class - to find topper out of 10 students
Swarup Boro
 
Array using recursion
Array using recursionArray using recursion
Array using recursion
Swarup Boro
 
Binary addition using class concept in c++
Binary addition using class concept in c++Binary addition using class concept in c++
Binary addition using class concept in c++
Swarup Boro
 
Study of Diffusion of solids in Liquids
Study of Diffusion of solids in Liquids                                 Study of Diffusion of solids in Liquids
Study of Diffusion of solids in Liquids
Swarup Boro
 
Program using function overloading
Program using function overloadingProgram using function overloading
Program using function overloading
Swarup Boro
 
Program to sort array using insertion sort
Program to sort array using insertion sortProgram to sort array using insertion sort
Program to sort array using insertion sort
Swarup Boro
 
Program to find the avg of two numbers
Program to find the avg of two numbersProgram to find the avg of two numbers
Program to find the avg of two numbers
Swarup Boro
 
Program to find factorial of a number
Program to find factorial of a numberProgram to find factorial of a number
Program to find factorial of a number
Swarup Boro
 
Canteen management program
Canteen management programCanteen management program
Canteen management program
Swarup Boro
 
C++ program using class
C++ program using classC++ program using class
C++ program using class
Swarup Boro
 
Railway reservation
Railway reservationRailway reservation
Railway reservation
Swarup Boro
 
Boolean
BooleanBoolean
Boolean
Swarup Boro
 
Classes
ClassesClasses
Classes
Swarup Boro
 
Constructor & destructor
Constructor & destructorConstructor & destructor
Constructor & destructor
Swarup Boro
 
Arrays and library functions
Arrays and library functionsArrays and library functions
Arrays and library functions
Swarup Boro
 
Pointers
PointersPointers
Pointers
Swarup Boro
 
Queue
QueueQueue
Structures in c++
Structures in c++Structures in c++
Structures in c++
Swarup Boro
 
Stack
StackStack

More from Swarup Boro (20)

Concatenation of two strings using class in c++
Concatenation of two strings using class in c++Concatenation of two strings using class in c++
Concatenation of two strings using class in c++
 
Program: Inheritance in Class - to find topper out of 10 students
Program: Inheritance in Class - to find topper out of 10 studentsProgram: Inheritance in Class - to find topper out of 10 students
Program: Inheritance in Class - to find topper out of 10 students
 
Array using recursion
Array using recursionArray using recursion
Array using recursion
 
Binary addition using class concept in c++
Binary addition using class concept in c++Binary addition using class concept in c++
Binary addition using class concept in c++
 
Study of Diffusion of solids in Liquids
Study of Diffusion of solids in Liquids                                 Study of Diffusion of solids in Liquids
Study of Diffusion of solids in Liquids
 
Program using function overloading
Program using function overloadingProgram using function overloading
Program using function overloading
 
Program to sort array using insertion sort
Program to sort array using insertion sortProgram to sort array using insertion sort
Program to sort array using insertion sort
 
Program to find the avg of two numbers
Program to find the avg of two numbersProgram to find the avg of two numbers
Program to find the avg of two numbers
 
Program to find factorial of a number
Program to find factorial of a numberProgram to find factorial of a number
Program to find factorial of a number
 
Canteen management program
Canteen management programCanteen management program
Canteen management program
 
C++ program using class
C++ program using classC++ program using class
C++ program using class
 
Railway reservation
Railway reservationRailway reservation
Railway reservation
 
Boolean
BooleanBoolean
Boolean
 
Classes
ClassesClasses
Classes
 
Constructor & destructor
Constructor & destructorConstructor & destructor
Constructor & destructor
 
Arrays and library functions
Arrays and library functionsArrays and library functions
Arrays and library functions
 
Pointers
PointersPointers
Pointers
 
Queue
QueueQueue
Queue
 
Structures in c++
Structures in c++Structures in c++
Structures in c++
 
Stack
StackStack
Stack
 

Recently uploaded

South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)
Academy of Science of South Africa
 
A Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdfA Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdf
Jean Carlos Nunes Paixão
 
Top five deadliest dog breeds in America
Top five deadliest dog breeds in AmericaTop five deadliest dog breeds in America
Top five deadliest dog breeds in America
Bisnar Chase Personal Injury Attorneys
 
Liberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdfLiberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdf
WaniBasim
 
Azure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHatAzure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHat
Scholarhat
 
MARY JANE WILSON, A “BOA MÃE” .
MARY JANE WILSON, A “BOA MÃE”           .MARY JANE WILSON, A “BOA MÃE”           .
MARY JANE WILSON, A “BOA MÃE” .
Colégio Santa Teresinha
 
Your Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective UpskillingYour Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective Upskilling
Excellence Foundation for South Sudan
 
How to Build a Module in Odoo 17 Using the Scaffold Method
How to Build a Module in Odoo 17 Using the Scaffold MethodHow to Build a Module in Odoo 17 Using the Scaffold Method
How to Build a Module in Odoo 17 Using the Scaffold Method
Celine George
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
TechSoup
 
Digital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments UnitDigital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments Unit
chanes7
 
Executive Directors Chat Leveraging AI for Diversity, Equity, and Inclusion
Executive Directors Chat  Leveraging AI for Diversity, Equity, and InclusionExecutive Directors Chat  Leveraging AI for Diversity, Equity, and Inclusion
Executive Directors Chat Leveraging AI for Diversity, Equity, and Inclusion
TechSoup
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
heathfieldcps1
 
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptxC1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
mulvey2
 
PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.
Dr. Shivangi Singh Parihar
 
DRUGS AND ITS classification slide share
DRUGS AND ITS classification slide shareDRUGS AND ITS classification slide share
DRUGS AND ITS classification slide share
taiba qazi
 
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
National Information Standards Organization (NISO)
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
Peter Windle
 
The History of Stoke Newington Street Names
The History of Stoke Newington Street NamesThe History of Stoke Newington Street Names
The History of Stoke Newington Street Names
History of Stoke Newington
 
Main Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docxMain Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docx
adhitya5119
 
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdfANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
Priyankaranawat4
 

Recently uploaded (20)

South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)
 
A Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdfA Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdf
 
Top five deadliest dog breeds in America
Top five deadliest dog breeds in AmericaTop five deadliest dog breeds in America
Top five deadliest dog breeds in America
 
Liberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdfLiberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdf
 
Azure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHatAzure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHat
 
MARY JANE WILSON, A “BOA MÃE” .
MARY JANE WILSON, A “BOA MÃE”           .MARY JANE WILSON, A “BOA MÃE”           .
MARY JANE WILSON, A “BOA MÃE” .
 
Your Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective UpskillingYour Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective Upskilling
 
How to Build a Module in Odoo 17 Using the Scaffold Method
How to Build a Module in Odoo 17 Using the Scaffold MethodHow to Build a Module in Odoo 17 Using the Scaffold Method
How to Build a Module in Odoo 17 Using the Scaffold Method
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
 
Digital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments UnitDigital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments Unit
 
Executive Directors Chat Leveraging AI for Diversity, Equity, and Inclusion
Executive Directors Chat  Leveraging AI for Diversity, Equity, and InclusionExecutive Directors Chat  Leveraging AI for Diversity, Equity, and Inclusion
Executive Directors Chat Leveraging AI for Diversity, Equity, and Inclusion
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
 
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptxC1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
 
PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.
 
DRUGS AND ITS classification slide share
DRUGS AND ITS classification slide shareDRUGS AND ITS classification slide share
DRUGS AND ITS classification slide share
 
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
 
The History of Stoke Newington Street Names
The History of Stoke Newington Street NamesThe History of Stoke Newington Street Names
The History of Stoke Newington Street Names
 
Main Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docxMain Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docx
 
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdfANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
 

1D Array

  • 1. Page 1 of 14 Array Areas Covered on: 1- D ARRAY . Definition of 1-D array. Implementation of 1-D array Basic operations of 1-D array Insertion & Deletion . Searching Sorting . Merging 1-D Array Definations: One dimensional array comprise of finite homogeneous elements represented as: Array name [Lower bound L, Upper bound U] ranges from L through U. To calculate array size (length) =U-L+1 Ex: Ar [-9, 15] Size=15-(-9) +1=23 Implementation of 1-D array: It is done to calculate address of any element in an array. Address of element with subscript I=Base address +ES (I-L) Where ES is size of an array element L is the lower bound of the array. Prepared By Sumit Kumar Gupta, PGT Computer Science
  • 2. Page 2 of 14 Basic operations of 1-D array:--1. Insertion & Deletion 2. Searching 3. Sorting 4. Merging Insertion: placing of new element within the existing array. Insertion is done in two ways: i) If the array is unordered, placing the new element at the end of the array. ii)if the array is sorted then new element is added at appropriate position. Algorithm: 1.ctr=L 2.If LST=U then { Print “Overflow:” Exit from program } 3. if AR[ctr]>ITEM then Pos=1 Else { 4. Repeat steps 5 and 6 until ctr>=U 5. if AR[ctr]<=ITEM and ITEM<=AR[ctr+1] then { Pos=ctr+1 Break } 6. ctr=ctr+1 /*end of repeat here*/ 7. if ctr=U then Pos=U+1 } /*end of if step 3 */ /* shift the element to create space*/ 8. ctr=U 9.while ctr>=pos perform steps 10 through 11 10.AR[ctr+1]=AR[ctr] Prepared By Sumit Kumar Gupta, PGT Computer Science
  • 3. Page 3 of 14 11.ctr=ctr=ctr-1 } 12. AR[pos]=ITEM 13. END Using Function: int FindPos(int AR[],int size,int item) /*to determine the position for element { int pos; if(item<AR[0]) pos=0; else { for(int i=0;i<size-1;i++) { if(AR[i]<=item && item <AR[i+1] { Pos=i+1; Break; } if(i==size-1) pos=size; } return pos; } Deletion: To delete an element from existing array. Algorithm: /*considering that Item’s search in array AR is successful at location pos*/ Two cases arises: Case1: Shifting Upward or left side 1. ctr=pos 2. Repeat steps 3 and 4 until ctr>=U 3. AR [ctr] =AR [ctr-1] 4. ctr=ctr+1 Prepared By Sumit Kumar Gupta, PGT Computer Science
  • 4. Page 4 of 14 /*end of repeat*/ Case II: shifting downwards (or in right side) 1. Ctr=pos 2. Repeat steps 3 and 4 until Ctr<=L 3.AR[ctr]=AR[ctr-1] 4.ctr=ctr-1 /*End of Repeat*/ Searching: Linear search: Linear search method is used to scan the array in a sequential manner.Under this method the whole array is searched one by one until the matching element is obtained . Note: Linear search is done in Unordered array. Algorithm: /*Initialise counter by assigning lower bound value of the array*/ Step1:Set ctr=L (Lower bound=0 in c++) /*Now search for the ITEM*/ Step2: Repeat steps 3 through 4 until ctr>U //Upper Bound(U) is size-1 Step3: if AR [ctr]==ITEM then { Print “search Successful” Print ctr,”is the location of”,ITEM Break } Step 4: ctr=ctr+1 /*End of repeat*/ Step 5 if ctr>U then Print “search Unsuccessful!” Step 6 END Using Function: Int LSearch(int AR[],int size,int item) { For(int i=0;i<size;i++) { Prepared By Sumit Kumar Gupta, PGT Computer Science
  • 5. Page 5 of 14 If(AR[i]==item) return i; } return -1; } Binary search: Steps:To search for ITEM in sorted array (in ascending order) 1. ITEM is compared with middle element of the segment(i.e,in the entire array for the first time). 2.If the ITEM is more than the middle element ,latter part of the segment becomes new segment to be scanned. 3.The same process is repeated for the new segment(s) until the item is found(search successful) or the segment is reduced to the single element and the ITEM is not found(search Unsuccessful). Condition: Array should be in sorted manner Using Function: int Bsearch(int AR[10], int I, int N) { int beg=0, last = N-1,Mid; While(beg<=last) { Mid =(beg+last)/2; If (AR[Mid]==I) Return 1; Else if (I > AR[Mid]) Beg=Mid+1; Else Last=Mid-1; } return 0; } Sorting: Selection Sorting: Steps: Prepared By Sumit Kumar Gupta, PGT Computer Science
  • 6. Page 6 of 14 Pass-1 Find the location LOC of the smallest in the list of n elements. a[1],a[2],……..a[n],then interchange a[loc]with a[1]. Pass-2 Find the location LOC and then interchanged a [LOC] and a [2].since a[1]<=a[2] Pass-3 Find the location LOC of the smallest in the sublist of n-2 elements. a [3],a[4],……a[n], and then interchanged a[LOC] and a[3].Then a[1],a[2]….a[3] is stored, since a[2]<=a[3] --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Pass N-1: Find the location LOC of the smallest of the elements a[n-],a[n] and interchanged a[LOC] and a[n-1].Then: a [1],a[2]….a[n] is strored, since a[n-1]<=a[n] Thus a is sorted after n-1 passes Algorithm: 1. small=AR[L] 2. For i=L to U do { 3. small=AR[i] 4. for J=I to U do { 5. If AR[j]<small then 6. { Small==AR[j] 7. Pos=j } j=j+1; } //In c++ ,0 to size-1 /*end of inner loop*/ /*swap the smallest element with ith element */ 8. temp=AR[i] 9. AR[i]=small 10. AR[pos]=temp } 11. END Prepared By Sumit Kumar Gupta, PGT Computer Science
  • 7. Page 7 of 14 Using Function : Void SelSort(int AR[],int size) { int small, pos,tmp; for(int i=0;i<size;i++) { small=AR[i]; for(int j=i+1;j<size;j++) { if(AR[j]<small) { small=AR[j]; pos=j; } } tmp=AR[i]; AR[i]=AR[pos]; AR[pos]=tmp; cout<<”n Array after pass –“<<i+1<<”—is :”; for(j=0;j<size;j++) cout<<AR[j]<<””; } } Bubble Sort The basic idea of bubble sort is to compare two adjoining values and exchange them if they are not in proper order. Algorithm: 1. For I=L to U 2. { For j=to [(U-1)-I] { Prepared By Sumit Kumar Gupta, PGT Computer Science
  • 8. Page 8 of 14 3. If AR[j]>AR[j+1] then { temp=AR[j] AR[j]=AR[j+1] AR[j+1]=temp } 4. 5. 6. } } 7. END Using Function Void BubbleSort(int AR[],int size) { int tmp,ctr=0; for(int i=0;i<size;i++) { for (int j=0;j<(size-1)-i;j++) { if(AR[j]<AR[j+1]) { tmp=AR[j]; AR[j]=Ar[j+1]; AR[j+1]=tmp; } } cout<<”Array after iteration—“<<++ctr<<”--: “; for(int k=0;k<size;k++) cout<<AR[k]<<””; cout<<endl } } Insertion sorting: Condition: Introduce a sentinel element A [0] = - ∞ (or a very small number) An insertion sort is one that sorts a set of values by inserting values into an existing sorted file. Prepared By Sumit Kumar Gupta, PGT Computer Science
  • 9. Page 9 of 14 The insertion sort algorithm scans array a from a[1] to a[n], inserting each element A[k] into its proper position on the previously sorted subarray a [1],a [2]...a [k1]. Using Function: Void InsSort (int AR [], int size) { int tmp,j; AR [0] =INT_MIN; for (int i=1;i<=size;i++) { tmp=AR[i]; j=i-1; while(tmp<AR[j]) { AR[j+1]=AR[j]; j--; } AR[j+1]=tmp; cout<<”Array after iteration—“<<++ctr<<”--: “; for (int k=0;k<size;k++) cout<<AR[k]<<””; cout<<endl; } } Merging: Merging means combining elements of two arrays to form a new array. Merging in array /* Merging of two array A and B where A is in ascending order ,B is in ascending order and resultant array C will be in Ascending ctr A=L1 ctr B=L2 ctr C=L3 while (ctr A<=U1) &&( ctr B<=U2) { If(A[ctr A]<=B[ctr B]) then Prepared By Sumit Kumar Gupta, PGT Computer Science
  • 10. Page 10 of 14 { C[ctr C]=A[ctr A] ctr C=ctr C + 1 ctr A=ctr A+1 } else { C[ctr C]=B[ctr B] ctr C=ctr C+1 ctr B=ctr B+1 }/*end of while loop If(ctr A >U1) then { While(ctr B <=U2) { C[ctrC]=B[ctr B] ctrC=ctrC+1 ctr B=ctr B+1 } } If(ctr B>U2) then { While (ctr A<=U1) { C[ctr C]=A[ctr A] ctr C=ctr C+1 ctr A=ctr A+1 } } There are some other cases are also possible .These cases are taken place in following situations: 1. When array A[n] is in Acsending order then its control variable ,say ctr A ,should be initialized with array’s lower bound ,which is 0(zero).And the test condition will be ctr<n. 2. When an array ,say A[n] ,is in descending order,then its control variable ,say ctr A ,should be initialized with array’s upper bound,which is n-1. Prepared By Sumit Kumar Gupta, PGT Computer Science
  • 11. Page 11 of 14 Assuming length of array A is M and Length of array B is N-1 . Thus array A has elements A[0] to A[N-1] and B has elements B[0] to B[N-1] .let the resultant array be C with length 10. CtrB=n-1 , ctrA=0 , ctrC=0 while (ctrC<5) do { C[ctrC]=A[ctrA] ctrC=ctrC+1 ctrA=ctrA+1 } while (ctrC<10) do { C[ctrC]=B[ctrB] ctrC=ctrC+1 ctrB=ctrB-1 } ctrC=0 while(ctrC<10) do { print C[ctrC] ctrC= ctrC+1 } END Solved Examples: Q.1 What do you understand by Data Structure. Describe about the types of data structure Ans A data Structure is a named group of data of different data types which can be processed as single unit. There are two types of data structure a. Simple :- i. Array ii. Structure b. Complex i. Linear :- i.Stack ii. Queue iii. Linked-list ii. Non-Linear : Tree Q.2What will be the address of 5th element in a floating point array implemented in C++?The array is specified as amount[16].the base address of the array is 1058. Ans) Standard size of floating-point array=4 bytes 5th element in the array Amount is specified as Amount[4] as the index numbers in c++ starts from 0. Address of Amount[4]=base address +es(I-L) L=0 Prepared By Sumit Kumar Gupta, PGT Computer Science
  • 12. Page 12 of 14 Es=4 Base Address=1058 Putting all these values, Address of Amount[4]=1058+4(4-0)=1074 Q.3 Suppose a one dimentional Array AR containing integers is arranged in ascending order .Write a user defined function in C++ to search for one integer from AR with the help of Binary Search Method , returning an integer 0 to show absence of the number and 1 to show the presence of the number in the array. The function should have three parameters (1. an array AR 2. the number to be searched 3. the number of elements N) Ans. Int Bsearch(int AR[10], int I, int N) { int beg=0, last = N-1,Mid; While(beg<=last) { Mid =(beg+last)/2; If (AR[Mid]==I) Return 1; Else if (I > AR[Mid]) Beg=Mid+1; Else Last=Mid-1; } return 0; } Practice also For Descending order Q.4 Write a function in C++ which accepts an integer array and its size as arguments and exchange the values of first half side element with the second half elements of the array. Example if an array of 10 elements has initial content 12,15,45,23,34,43,77,46,35,47 The resultant array should be like this 43,77,46,35,47,12,15,45,23,34 Ans void swap( int A[ ] ,int size) { int I,j,temp,mid=size/2; if (size %2 = = 0) j=mid ; else j=mid+1; for(i=0;i<mid;i++,j++) { temp= A[i]; Prepared By Sumit Kumar Gupta, PGT Computer Science
  • 13. Page 13 of 14 A[i]=A[j]; A[j]=temp; } } 5. Write an Algorithm for Selection Sort . Ans : 1. small=AR[L] 2. for i= L to U loop 3. { small = AR[i] 4. for j = I to U do 5. { if AR[j] < small then 6. { small = AR[j] 7. pos = j } 8. j = j + 1 } 9. temp = AR[i] 10. AR[i] = small 11. AR[pos] = temp } 12. end Q.6 An algorithm requires two stacks of size M and N that are to be maintained in the memory .Illustrate with an example how will you adjust two stacks in one dimensional array with M+N memory locations so that the overflow condition is minimized . Ans . let us say that the stack A is with size M and Stack B with size N If the stack A is stored in locations 0 to M-1 and the stack B is stored in locations M to M+N-1 ,the separate areas for the two are ensured .in the beginning the tops of the stacks are at opposite ends . when Top A reaches at M-1 , any further insertion will lead to overflow in stack A and when Top B reaches at M. any further insertion in stack B will lead to overflow. Q.7 Given two arrays A and B ,copy last five element of B after first five element of A to create another array C. Assume length of A and B is greater than 5.(Merge Sort) Ans Assuming length of array A is M and Length of array B is N-1 . thus array A has elements A[0] to A[N-1] and B has elements B[0] to B[N-1] .let the resultant array be C with length 10. ctrB=n-1 , ctrA=0 , ctrC=0 while (ctrC<5) do { C[ctrC]=A[ctrA] ctrC=ctrC+1 ctrA=ctrA+1 } while (ctrC<10) do { C[ctrC]=B[ctrB] ctrC=ctrC+1 Prepared By Sumit Kumar Gupta, PGT Computer Science
  • 14. Page 14 of 14 ctrB=ctrB-1 } ctrC=0 while(ctrC<10) do { print C[ctrC] ctrC= ctrC+1 } END | Prepared By Sumit Kumar Gupta, PGT Computer Science