SlideShare a Scribd company logo
Data Structures & Algorithms
By
Dr. Prakash Singh Tanwar
Associate Professor
Lovely Professional University, Punjab
Topic: Linear Arrays Memory
Representations
Linear Arrays Memory
Representation
Basic Terminology
Linear Array
Memory Representation of Linear Array
Traversing Array
Insertion and Deletion in Array
Sorting (Bubble Sort)
Searching (Linear Search and Binary Search)
Review Questions
By:Dr. Prakash Singh Tanwar
Basic Terminology
Linear Data Structures:
A data structure is said to be linear if its elements form a
sequence or a linear list.
Linear Array:
It is a list of a finite number n of homogeneous data
elements (same type of data elements) such that:
• (a) the elements of the array are referenced by an index set
consisting of n consecutive numbers.
• (b) the elements of the array are stored respectively in successive
memory locations
By:Dr. Prakash Singh Tanwar
Revision
Definition
Array is a group of variables of same data type
having a common name.
Elements of an array can be accessed through
its subscript(0 to n-1) where n is the size of
array.
Continous memory allocation
By:Dr. Prakash Singh
Tanwar
Revision: 1D Array
A single- dimensional or 1-D array consists of
a fixed number of elements of the same data
type organized as a single linear sequence.
Array declaration
Syntax
Ex
<data_type> <array_name>[<size>];
int a[5];
char name[20];
float num[4];
By:Dr. Prakash Singh Tanwar
Revision: 1D Array
Array declaration
a[0] a[1] a[2] a[3] a[4]
20
int a[5];
a[0]=9;
a[1]=6;
a[2]=7;
a[3]=5;
a[4]=20;
9 6 7 5
By:Dr. Prakash Singh Tanwar
1D Array Memory
Representation
Array declaration
a[0] a[1] a[2] a[3] a[4]
20
int a[5];
a[0]=9;
a[1]=6;
a[2]=7;
a[3]=5;
a[4]=20;
9 6 7 5
1001 1003 1005 1007 1009
size of int = 2 bytes
&a[0]= 1001
&a[1]= 1001+2=1003
&a[2]= 1003+2=1005
&a[3]= 1005+2=1007
&a[4]= 1007+2=1009
size of int = 2 bytes
&a[0]= 1001
&a[1]= 1001+2=1003
&a[2]= 1003+2=1005
&a[3]= 1005+2=1007
&a[4]= 1007+2=1009
Note: size of int in 32 bit compiler =2 bytes
Note: size of int in 32 bit compiler =2 bytes
By:Dr. Prakash Singh Tanwar
1D Array Memory
Representation
Array declaration
a[0] a[1] a[2] a[3] a[4]
20
int a[5];
a[0]=9;
a[1]=6;
a[2]=7;
a[3]=5;
a[4]=20;
9 6 7 5
1001 1005 1009 1013 1017
size of int = 4 bytes
&a[0]= 1001
&a[1]= 1001+4=1005
&a[2]= 1005+4=1009
&a[3]= 1009+4=1013
&a[4]= 1013+4=1017
size of int = 4 bytes
&a[0]= 1001
&a[1]= 1001+4=1005
&a[2]= 1005+4=1009
&a[3]= 1009+4=1013
&a[4]= 1013+4=1017
Note: size of int in 64 bit compiler =4 bytes
Note: size of int in 64 bit compiler =4 bytes
By:Dr. Prakash Singh Tanwar
Q/A
Are these valid statements?
int a[10];
a[10]=10;
a[10]=10; is not valid
Because, in array a[10] we have only 10 elements
from a[0] to a[9]
By:Dr. Prakash Singh Tanwar
1D Array Memory
Representation
Array declaration
Size of char
• 1 byte
Ex
• Array Size
4 characters
• Subscript
0 to 3
n[0] n[1] n[2] n[3]
char n[4];
5001 5002 5003 5004
size of array
By:Dr. Prakash Singh Tanwar
Basic Terminology
Size / Length of Array
Index of Array
Upper bound and Lower bound of Array
By:Dr. Prakash Singh Tanwar
a[0] a[1] a[2] a[3] a[4]
Size / Length of Array=5
Index of array : 0 to 4
Lower Bound Upper Bound
Traversing Linear Array
Suppose we have to count the number of element in an
array or print all the elements of array.
By:Dr. Prakash Singh Tanwar
Algorithm 1: (Using While Loop)
1. [Initialize Counter.] Set K = LB.
2. Repeat Step 3 and 4 while K<= UB.
3. [Visit Element.] Apply PROCESS to A[K].
4. [Increase Counter.] Set K = K+1.
[End of Step 2 Loop.]
5. Exit.
a[0] a[1] a[2] a[3] a[4]
20
9 6 7 5
K
LB UB
Traversing Linear Array
Algorithm 2: (Using for loop)
By:Dr. Prakash Singh Tanwar
1. Repeat for K = LB to UB
Apply PROCESS to A[K].
[ End of Loop.]
2. Exit.
a[0] a[1] a[2] a[3] a[4]
20
9 6 7 5
K
LB UB
Q/A
Question.1: Find the Number of elements in an array
which are greater than 25
Question 2: Find out the sum of all the two digit
numbers in an array.
By:Dr. Prakash Singh Tanwar
a[0] a[1] a[2] a[3] a[4]
20
25 6 27 5
K
LB UB
Insertion in an Array
Two types of insertion are
possible:
Insertion at the end of array
Insertion in the middle of the array
By:Dr. Prakash Singh Tanwar
Insert an element in an
Array
Write a program to insert an element in
an array?
Where to insert?
What are the current elements in the array?
What value you want to insert?
How many elements are there in this array?
a[0] a[1] a[2] a[3] a[4]
10 20 30
By:Dr. Prakash Singh Tanwar
Insertion in an Array
Algorithm: (Insertion of an element ITEM into Kth position in a Linear
Array A with N elements)
By:Dr. Prakash Singh Tanwar
Input:
A: Array A ; N: Array A have N elements in it
ITEM :item to insert ; Pos: insert item at position Pos
Output:
Array A with item inserted at position index ‘Pos’
Algorithm
1. [Initialize Counter.] Set I = N.
2. Repeat Steps 3 and 4 while I >= Pos.
3. [Move Ith element downward] Set A[I+1] = A[I].
4. [Decrease Counter.] Set I = I-1.
[End of Step 2 loop]
5. [Insert element.] Set A[Pos] = ITEM.
6. [Reset N] N = N+1.
7. Exit
Insert an element in an
Array
Insert 15 at pos index=1, Size=3
a[0] a[1] a[2] a[3] a[4]
10 20 30
a[0] a[1] a[2] a[3] a[4]
10 20 30 30
a[0] a[1] a[2] a[3] a[4]
10 20 20 30
a[0] a[1] a[2] a[3] a[4]
10 15 20 30
A[I+1]=A[I]
A[I+1]=A[I]
Algorithm(for index starting from 1)
1. [Initialize Counter.] Set I = N.
2. Repeat Steps 3 and 4 while I >= Pos.
3. [Move Ith element downward] Set A[I+1] = A[I].
4. [Decrease Counter.] Set I = I-1.
[End of Step 2 loop]
5. [Insert element.] Set A[Pos] = ITEM.
6. [Reset N] N = N+1.
7. Exit
I
A[Pos]=ITEM
Algorithm (for index starting from 0 and pos is also in the
form of index)
1. [Initialize Counter.] Set I = N-1.
2. Repeat Steps 3 and 4 while I >=Pos.
3. [Move Ith element downward] Set A[I+1] = A[I].
4. [Decrease Counter.] Set I = I-1.
[End of Step 2 loop]
5. [Insert element.] Set A[Pos] = ITEM.
6. [Reset N] N = N+1.
7. Exit
By:Dr. Prakash Singh Tanwar
Insert an element in an
Array
int insert(int a[], int n, int key, int pos)
{
int i;
//shift the elements to right
for(i=n-1;i>=pos; i--)
{
a[i+1]=a[i];
}
//insert the element
a[pos]=key;
//increase the size
n++;
return n;
}
//display array
printf("n After insertion in arrayn");
for(i=0;i<size;i++)
{
printf("%dt",a[i]);
}
By:Dr. Prakash Singh Tanwar
cout<<"n After insertion in array“<<endl;
cout<<a[i]<<“t”;
int main(void)
{
int arr[6] = { 10,20,30 };
int n = 3;
int key=15;
int pos=1;
//insert element key at given pos
n=insert(arr,n,key,pos);
//display array
display(arr,n);
return 0;
}
Linear Search
Write a program to search an element in
an array?
What are the current elements in the array?
What value you want to search?
By:Dr. Prakash Singh
Tanwar
a[0] a[1] a[2] a[3] a[4]
10 8 30 5 60
Linear Search
(un-ordered data)
Input:
Array a[] with size n
Key to search
Output :
pos index of key element in the array. If not found then return -1
Algo:
Start searching the element from the left most position to the end of an array.
• If key element is found the return the position index
• Otherwise repeat the step 1 for next position
If it is not found in all position index of array then
• return not found
By:Dr. Prakash Singh
Tanwar
Linear Search
(un-ordered data)
Search key=15
By:Dr. Prakash Singh
Tanwar
a[0] a[1] a[2] a[3] a[4]
10 8 30 5 60
i=0
i=0
a[i]==key
Not
matched
i=1
i=1
Not
matched
i=2
i=2
Not
matched
i=3
i=3
Not
matched
i=4
i=4
Not
matched
i=5 (out)
i=5 (out)
Key=15
Linear Search
(un-ordered data)
Search key= 30
a[0] a[1] a[2] a[3] a[4]
10 8 30 5 60
i=0
i=0
a[i]==key
a[i]==30
Not
matched
i=1
i=1
Not
matched
i=2
i=2
Matched
30 is found at pos i=2
Key=30
By:Dr. Prakash Singh Tanwar
Linear Search
(un-ordered data)
// linear search for unordered data
int linearSearch(int a[], int size, int key)
{
int i;
//check each element to search the key
for(i=0; i < size ; i++)
{
//if key is found in array
if( a[i] == key )
{
return i; // then return the pos i
}
}
//if not found then return -1
return -1;
}
By:Dr. Prakash Singh Tanwar
Linear Search
(Sorted Array)
// linear search for ordered data
int linearSearch(int a[], int size, int key)
{
int i;
//check each element to search the key
for(i=0; i<size && a[i]<=key ;i++)
{
//if key is found in array
if( a[i] == key )
{
return i;// then return the pos i
}
}
//if not found then return -1
return -1;
}
By:Dr. Prakash Singh Tanwar
Linear Search
(Sorted Array)
Linear Search (sorted array)
a[0] a[1] a[2] a[3] a[4]
10 20 30 40 50
i=0
i=0 i=1
i=1
key= 30
Key not
matched
30<10
=false
Key not
matched
30<20
=false
10==30 20==30
i=2
i=2
Key
matched
30==30
Try next
element
Try next
element
30 found at
pos i=2
By:Dr. Prakash Singh Tanwar
Linear Search
(Sorted Array)
Linear Search (sorted array)
a[0] a[1] a[2] a[3] a[4]
10 20 30 40 50
i=0
i=0 i=1
i=1
key= 25
Key not
matched
25<10
=false
Key not
matched
25<20
=false
10==25 20==25
i=2
i=2
Key not
matched
30==25
Try next
element
Try next
element 25 not found in
sorted array
25<30
=true
Come
out from
loop
Where the control will move
from this break statement?
By:Dr. Prakash Singh Tanwar
Q/A
Where the control will move from this break statement?
A. Out side of loop
B. come out from if
C. Come out from else if
D. move to increment section
By:Dr. Prakash Singh Tanwar
Linear Search
(Sorted Array)
// linear search for ordered data
int linearSearch(int a[], int size, int key)
{
int i;
//check each element to search the key
for(i=0; i<size && a[i]<=key ;i++)
{
//if key is found in array
if( a[i] == key )
{
return i;// then return the pos i
}
}
//if not found then return -1
return -1;
}
Both program works same
Both program works same
Opposite
condition
By:Dr. Prakash Singh Tanwar
Q/A
It can search sorted and unsorted elements both
best case : key is found at the first element (index=0):
Ω (1)
worst case: key element is found at last position n
(index=n-1) : O(n)
By:Dr. Prakash Singh Tanwar
Q/A
What is the best case search order for
linear search?
A. Ω(1)
B. O(n)
C.O(n2)
D. Ω(n)
By:Dr. Prakash Singh Tanwar
Q/A
What is the best case search order for
linear search?
A. Ω(1)
B. O(n)
C.O(n2)
D. Ω(n)
By:Dr. Prakash Singh Tanwar
Q/A
What is the worst case search order for
linear search?
A. Ω(1)
B. O(n)
C.O(n2)
D. Ω(n)
By:Dr. Prakash Singh Tanwar
Q/A
What is the worst case search order for
linear search?
A. O(1)
B. O(n)
C.O(n2)
D. Ω(n)
By:Dr. Prakash Singh Tanwar
Q/A
Which of the program is correct for linear search algorithm?
A B C D
int index = -1;
int i = 0;
while(size > 0)
{
if(a[i] == key)
{
index = i;
}
if(a[i] > key))
{
index = i;
break;
}
i++;
}
return index;
int index = -1;
int i = 0;
while(size > 0)
{
if(a[i] == key)
{
index = i;
break;
}
if(a[i] > key))
{
break;
}
i++;
}
return index;
int index = -1;
int i = 0;
while(size > 0)
{
if(a[i] == key)
{
index=i;
break;
}
if(a[i] > key))
{
index = i;
}
i++;
}
return index;
int index = -1;
int i = 0;
while(size > 0)
{
if(a[i] == key)
{
break;
}
if(a[i] > key))
{
break;
index = i;
}
i++;
}
return index;
By:Dr. Prakash Singh Tanwar
Q/A
Write a program to delete an element
from an array?
What are the current elements in the array?
What you wants to delete?
How many elements are there in this array?
a[0] a[1] a[2] a[3] a[4]
10 20 30
By:Dr. Prakash Singh Tanwar
Delete Element of an
array
Delete 10 , Size=3
Search 10 in this array using search algo.
a[0] a[1] a[2] a[3] a[4]
10 20 30
a[0] a[1] a[2] a[3] a[4]
20 20 30
a[0] a[1] a[2] a[3] a[4]
20 30 30
a[0] a[1] a[2] a[3] a[4]
20 30
Size--
a[0]=a[1]
a[1]=a[2]
posToDelete=0
By:Dr. Prakash Singh Tanwar
Delete Element of an
array
By:Dr. Prakash Singh Tanwar
Input: Pointer to an array a[], size of array, Key to delete
Output: array with deleted item and
size of array
Step1: posToDelete =search the element in the array and get the position
to delete
Step 2: if key not found
display message
Step 3: Otherwise (if key found in array)
replace the elements from posToDelete to the size of array
Step 3(a): repeat the step from last element to the posToDelete
Shift elements to the left hand side a[i]=a[i+1];
Step 3(b): decrease the size by one
size--;
Step 4 return the size
Delete Element of an
array
By:Dr. Prakash Singh Tanwar
cout<<“Element ” <<key<<“ not fount in array”<<endl;
cout<<“Before deletion of an array”<<endl;
cout<<“Which element you want to remove?”<<endl;
cin>> key;
cout<<“After deletion from array”<<endl;
Binary Search
a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8] a[9]
10 20 30 40 50 60 70 80 90 100
mid=(9+0)/2=4 Mid=4
Mid=4
Key=60
a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8] a[9]
10 20 30 40 50 60 70 80 90 100
Mid=(5+9)/2=7
Mid+1
Mid-1
Mid-1
Mid=(5+6)/2=5
Left=0
Left=0 Right=9
Right=9
key not found
key not found
a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8] a[9]
10 20 30 40 50 60 70 80 90 100
Mid=7
Mid=7 Mid+1
Mid+1
Mid-1
Mid-1
Left
=mid+1
Right
Right
key not found
key not found
Mid=5
Mid=5
key found at
pos 5
key found at
pos 5
Right
=mid-1
By:Dr. Prakash Singh Tanwar
Binary Search
Algorithm
Step 1: calculate the mid position
Step 2: If the key to search is found at mid then return the mid pos
Step 3: If key < a[mid] value, then it is in left side.
so, recursively find it in left side from left to mid - 1
Step 4: otherwise , then it is in right side.
so, recursively find it in right side i.e. from mid + 1 to right
Step 5: if it is not found in left and right then return -1 (not found)
By:Dr. Prakash Singh Tanwar
Binary Search
cout<<“key is not found in array” <<endl;
cout<<“key is found at index ”<<pos<<endl;
By:Dr. Prakash Singh Tanwar
Binary Search
cout<<“key is not found in array” <<endl;
cout<<“key is found at index ”<<pos<<endl;
By:Dr. Prakash Singh Tanwar
Binary Search-Algo-2
Algorithm
1. BINARY ( DATA, LB, UB, ITEM, LOC )
2. [Initialize Segment Variables]
Set BEG = LB, END = UB and MID = INT ((BEG+END)/2).
3. Repeat Steps 3 and 4 while BEG <= END and DATA [MID] != ITEM.
4. If ITEM < DATA[MID], then:
Set END = MID - 1.
Else:
Set BEG = MID + 1.
[End of if Structure.]
5. Set MID = INT ((BEG+END)/2).
[End of Step 2 Loop.]
6. If DATA [MID] = ITEM, then: Set LOC= MID
Else:
Set LOC = NULL.
[End of if structure.]
7. Exit.
By:Dr. Prakash Singh Tanwar
Binary Search
Binary search order is
O(log n )
If n=1024 then it will take max.
log2(1024)=log2(210) =10 steps
1024512256128643216
8421
By:Dr. Prakash Singh Tanwar
Q/A
If there are 1000 elements in an array. Then
how many maximum steps are needed to
search an element in an array using binary
search ?
A. 9
B. 1000
C. 999
D. 10
By:Dr. Prakash Singh Tanwar
Limitations of
Binary Search
Although the complexity of Binary Search is
O (log n), it has some limitations:
The list must be sorted
One must have direct access to the middle element in
any sublist.
By:Dr. Prakash Singh Tanwar

More Related Content

What's hot

Project of data structure
Project of data structureProject of data structure
Project of data structure
Umme habiba
 
Queue implementation
Queue implementationQueue implementation
Queue implementation
Rajendran
 
Insertion sort
Insertion sortInsertion sort
Insertion sort
almaqboli
 
Selection sort
Selection sortSelection sort
Selection sort
stella D
 
Merge sort algorithm power point presentation
Merge sort algorithm power point presentationMerge sort algorithm power point presentation
Merge sort algorithm power point presentation
University of Science and Technology Chitttagong
 
single linked list
single linked listsingle linked list
single linked list
Sathasivam Rangasamy
 
Binary Search
Binary SearchBinary Search
Binary Search
kunj desai
 
List in Python
List in PythonList in Python
List in Python
Siddique Ibrahim
 
Array data structure
Array data structureArray data structure
Array data structure
maamir farooq
 
Arrays
ArraysArrays
Selection sorting
Selection sortingSelection sorting
Selection sorting
Himanshu Kesharwani
 
Linear Search Data Structure
Linear Search Data StructureLinear Search Data Structure
Linear Search Data Structure
Talha Shaikh
 
Selection sort
Selection sortSelection sort
Selection sort
smlagustin
 
linked list in data structure
linked list in data structure linked list in data structure
linked list in data structure
shameen khan
 
Merge sort algorithm
Merge sort algorithmMerge sort algorithm
Merge sort algorithm
Shubham Dwivedi
 
Stack
StackStack
List,tuple,dictionary
List,tuple,dictionaryList,tuple,dictionary
List,tuple,dictionary
nitamhaske
 
Stacks in c++
Stacks in c++Stacks in c++
Stacks in c++
Vineeta Garg
 
Insertion sort
Insertion sort Insertion sort
Insertion sort
Monalisa Patel
 
Algorithm analysis
Algorithm analysisAlgorithm analysis
Algorithm analysis
sumitbardhan
 

What's hot (20)

Project of data structure
Project of data structureProject of data structure
Project of data structure
 
Queue implementation
Queue implementationQueue implementation
Queue implementation
 
Insertion sort
Insertion sortInsertion sort
Insertion sort
 
Selection sort
Selection sortSelection sort
Selection sort
 
Merge sort algorithm power point presentation
Merge sort algorithm power point presentationMerge sort algorithm power point presentation
Merge sort algorithm power point presentation
 
single linked list
single linked listsingle linked list
single linked list
 
Binary Search
Binary SearchBinary Search
Binary Search
 
List in Python
List in PythonList in Python
List in Python
 
Array data structure
Array data structureArray data structure
Array data structure
 
Arrays
ArraysArrays
Arrays
 
Selection sorting
Selection sortingSelection sorting
Selection sorting
 
Linear Search Data Structure
Linear Search Data StructureLinear Search Data Structure
Linear Search Data Structure
 
Selection sort
Selection sortSelection sort
Selection sort
 
linked list in data structure
linked list in data structure linked list in data structure
linked list in data structure
 
Merge sort algorithm
Merge sort algorithmMerge sort algorithm
Merge sort algorithm
 
Stack
StackStack
Stack
 
List,tuple,dictionary
List,tuple,dictionaryList,tuple,dictionary
List,tuple,dictionary
 
Stacks in c++
Stacks in c++Stacks in c++
Stacks in c++
 
Insertion sort
Insertion sort Insertion sort
Insertion sort
 
Algorithm analysis
Algorithm analysisAlgorithm analysis
Algorithm analysis
 

Similar to 03 Linear Arrays Memory Representations .pdf

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
 
Data Structures- Part3 arrays and searching algorithms
Data Structures- Part3 arrays and searching algorithmsData Structures- Part3 arrays and searching algorithms
Data Structures- Part3 arrays and searching algorithms
Abdullah Al-hazmy
 
Sorting
SortingSorting
Sorting
Samsil Arefin
 
searching in data structure.pptx
searching in data structure.pptxsearching in data structure.pptx
searching in data structure.pptx
chouguleamruta24
 
Searching
SearchingSearching
Searching
A. S. M. Shafi
 
1 D Arrays in C++
1 D Arrays in C++1 D Arrays in C++
1 D Arrays in C++
poonam.rwalia
 
datastructureppt-190327174340 (1).pptx
datastructureppt-190327174340 (1).pptxdatastructureppt-190327174340 (1).pptx
datastructureppt-190327174340 (1).pptx
DEEPAK948083
 
Chap10
Chap10Chap10
Chap10
Terry Yoast
 
CP PPT_Unit IV computer programming in c.pdf
CP PPT_Unit IV computer programming in c.pdfCP PPT_Unit IV computer programming in c.pdf
CP PPT_Unit IV computer programming in c.pdf
saneshgamerz
 
DSA Lec 5+6(Search+Sort) (1).pdf
DSA Lec 5+6(Search+Sort) (1).pdfDSA Lec 5+6(Search+Sort) (1).pdf
DSA Lec 5+6(Search+Sort) (1).pdf
MustafaJutt4
 
Unit III Version I.pptx
Unit III Version I.pptxUnit III Version I.pptx
Unit III Version I.pptx
ssuserd602fd
 
Searching techniques with progrms
Searching techniques with progrmsSearching techniques with progrms
Searching techniques with progrms
Misssaxena
 
Chapter 14
Chapter 14Chapter 14
Chapter 14
Terry Yoast
 
DS Unit 1.pptx
DS Unit 1.pptxDS Unit 1.pptx
DS Unit 1.pptx
chin463670
 
Searching and Sorting Algorithms in Data Structures
Searching and Sorting Algorithms  in Data StructuresSearching and Sorting Algorithms  in Data Structures
Searching and Sorting Algorithms in Data Structures
poongothai11
 
Lecture3b searching
Lecture3b searchingLecture3b searching
Lecture3b searching
mbadhi barnabas
 
Data structure ppt
Data structure pptData structure ppt
Data structure ppt
Prof. Dr. K. Adisesha
 
9 Arrays
9 Arrays9 Arrays
Array 2
Array 2Array 2
Array 2
Abbott
 
search_sort Search sortSearch sortSearch sortSearch sort
search_sort Search sortSearch sortSearch sortSearch sortsearch_sort Search sortSearch sortSearch sortSearch sort
search_sort Search sortSearch sortSearch sortSearch sort
Shanmuganathan C
 

Similar to 03 Linear Arrays Memory Representations .pdf (20)

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
 
Data Structures- Part3 arrays and searching algorithms
Data Structures- Part3 arrays and searching algorithmsData Structures- Part3 arrays and searching algorithms
Data Structures- Part3 arrays and searching algorithms
 
Sorting
SortingSorting
Sorting
 
searching in data structure.pptx
searching in data structure.pptxsearching in data structure.pptx
searching in data structure.pptx
 
Searching
SearchingSearching
Searching
 
1 D Arrays in C++
1 D Arrays in C++1 D Arrays in C++
1 D Arrays in C++
 
datastructureppt-190327174340 (1).pptx
datastructureppt-190327174340 (1).pptxdatastructureppt-190327174340 (1).pptx
datastructureppt-190327174340 (1).pptx
 
Chap10
Chap10Chap10
Chap10
 
CP PPT_Unit IV computer programming in c.pdf
CP PPT_Unit IV computer programming in c.pdfCP PPT_Unit IV computer programming in c.pdf
CP PPT_Unit IV computer programming in c.pdf
 
DSA Lec 5+6(Search+Sort) (1).pdf
DSA Lec 5+6(Search+Sort) (1).pdfDSA Lec 5+6(Search+Sort) (1).pdf
DSA Lec 5+6(Search+Sort) (1).pdf
 
Unit III Version I.pptx
Unit III Version I.pptxUnit III Version I.pptx
Unit III Version I.pptx
 
Searching techniques with progrms
Searching techniques with progrmsSearching techniques with progrms
Searching techniques with progrms
 
Chapter 14
Chapter 14Chapter 14
Chapter 14
 
DS Unit 1.pptx
DS Unit 1.pptxDS Unit 1.pptx
DS Unit 1.pptx
 
Searching and Sorting Algorithms in Data Structures
Searching and Sorting Algorithms  in Data StructuresSearching and Sorting Algorithms  in Data Structures
Searching and Sorting Algorithms in Data Structures
 
Lecture3b searching
Lecture3b searchingLecture3b searching
Lecture3b searching
 
Data structure ppt
Data structure pptData structure ppt
Data structure ppt
 
9 Arrays
9 Arrays9 Arrays
9 Arrays
 
Array 2
Array 2Array 2
Array 2
 
search_sort Search sortSearch sortSearch sortSearch sort
search_sort Search sortSearch sortSearch sortSearch sortsearch_sort Search sortSearch sortSearch sortSearch sort
search_sort Search sortSearch sortSearch sortSearch sort
 

Recently uploaded

smart pill dispenser is designed to improve medication adherence and safety f...
smart pill dispenser is designed to improve medication adherence and safety f...smart pill dispenser is designed to improve medication adherence and safety f...
smart pill dispenser is designed to improve medication adherence and safety f...
um7474492
 
Impartiality as per ISO /IEC 17025:2017 Standard
Impartiality as per ISO /IEC 17025:2017 StandardImpartiality as per ISO /IEC 17025:2017 Standard
Impartiality as per ISO /IEC 17025:2017 Standard
MuhammadJazib15
 
Object Oriented Analysis and Design - OOAD
Object Oriented Analysis and Design - OOADObject Oriented Analysis and Design - OOAD
Object Oriented Analysis and Design - OOAD
PreethaV16
 
Call For Paper -3rd International Conference on Artificial Intelligence Advan...
Call For Paper -3rd International Conference on Artificial Intelligence Advan...Call For Paper -3rd International Conference on Artificial Intelligence Advan...
Call For Paper -3rd International Conference on Artificial Intelligence Advan...
ijseajournal
 
DESIGN AND MANUFACTURE OF CEILING BOARD USING SAWDUST AND WASTE CARTON MATERI...
DESIGN AND MANUFACTURE OF CEILING BOARD USING SAWDUST AND WASTE CARTON MATERI...DESIGN AND MANUFACTURE OF CEILING BOARD USING SAWDUST AND WASTE CARTON MATERI...
DESIGN AND MANUFACTURE OF CEILING BOARD USING SAWDUST AND WASTE CARTON MATERI...
OKORIE1
 
Determination of Equivalent Circuit parameters and performance characteristic...
Determination of Equivalent Circuit parameters and performance characteristic...Determination of Equivalent Circuit parameters and performance characteristic...
Determination of Equivalent Circuit parameters and performance characteristic...
pvpriya2
 
Transformers design and coooling methods
Transformers design and coooling methodsTransformers design and coooling methods
Transformers design and coooling methods
Roger Rozario
 
SCALING OF MOS CIRCUITS m .pptx
SCALING OF MOS CIRCUITS m                 .pptxSCALING OF MOS CIRCUITS m                 .pptx
SCALING OF MOS CIRCUITS m .pptx
harshapolam10
 
4. Mosca vol I -Fisica-Tipler-5ta-Edicion-Vol-1.pdf
4. Mosca vol I -Fisica-Tipler-5ta-Edicion-Vol-1.pdf4. Mosca vol I -Fisica-Tipler-5ta-Edicion-Vol-1.pdf
4. Mosca vol I -Fisica-Tipler-5ta-Edicion-Vol-1.pdf
Gino153088
 
Open Channel Flow: fluid flow with a free surface
Open Channel Flow: fluid flow with a free surfaceOpen Channel Flow: fluid flow with a free surface
Open Channel Flow: fluid flow with a free surface
Indrajeet sahu
 
An Introduction to the Compiler Designss
An Introduction to the Compiler DesignssAn Introduction to the Compiler Designss
An Introduction to the Compiler Designss
ElakkiaU
 
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODELDEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
ijaia
 
原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样
原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样
原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样
ydzowc
 
Asymmetrical Repulsion Magnet Motor Ratio 6-7.pdf
Asymmetrical Repulsion Magnet Motor Ratio 6-7.pdfAsymmetrical Repulsion Magnet Motor Ratio 6-7.pdf
Asymmetrical Repulsion Magnet Motor Ratio 6-7.pdf
felixwold
 
一比一原版(osu毕业证书)美国俄勒冈州立大学毕业证如何办理
一比一原版(osu毕业证书)美国俄勒冈州立大学毕业证如何办理一比一原版(osu毕业证书)美国俄勒冈州立大学毕业证如何办理
一比一原版(osu毕业证书)美国俄勒冈州立大学毕业证如何办理
upoux
 
Tools & Techniques for Commissioning and Maintaining PV Systems W-Animations ...
Tools & Techniques for Commissioning and Maintaining PV Systems W-Animations ...Tools & Techniques for Commissioning and Maintaining PV Systems W-Animations ...
Tools & Techniques for Commissioning and Maintaining PV Systems W-Animations ...
Transcat
 
Bituminous road construction project based learning report
Bituminous road construction project based learning reportBituminous road construction project based learning report
Bituminous road construction project based learning report
CE19KaushlendraKumar
 
ITSM Integration with MuleSoft.pptx
ITSM  Integration with MuleSoft.pptxITSM  Integration with MuleSoft.pptx
ITSM Integration with MuleSoft.pptx
VANDANAMOHANGOUDA
 
AI + Data Community Tour - Build the Next Generation of Apps with the Einstei...
AI + Data Community Tour - Build the Next Generation of Apps with the Einstei...AI + Data Community Tour - Build the Next Generation of Apps with the Einstei...
AI + Data Community Tour - Build the Next Generation of Apps with the Einstei...
Paris Salesforce Developer Group
 
5G Radio Network Througput Problem Analysis HCIA.pdf
5G Radio Network Througput Problem Analysis HCIA.pdf5G Radio Network Througput Problem Analysis HCIA.pdf
5G Radio Network Througput Problem Analysis HCIA.pdf
AlvianRamadhani5
 

Recently uploaded (20)

smart pill dispenser is designed to improve medication adherence and safety f...
smart pill dispenser is designed to improve medication adherence and safety f...smart pill dispenser is designed to improve medication adherence and safety f...
smart pill dispenser is designed to improve medication adherence and safety f...
 
Impartiality as per ISO /IEC 17025:2017 Standard
Impartiality as per ISO /IEC 17025:2017 StandardImpartiality as per ISO /IEC 17025:2017 Standard
Impartiality as per ISO /IEC 17025:2017 Standard
 
Object Oriented Analysis and Design - OOAD
Object Oriented Analysis and Design - OOADObject Oriented Analysis and Design - OOAD
Object Oriented Analysis and Design - OOAD
 
Call For Paper -3rd International Conference on Artificial Intelligence Advan...
Call For Paper -3rd International Conference on Artificial Intelligence Advan...Call For Paper -3rd International Conference on Artificial Intelligence Advan...
Call For Paper -3rd International Conference on Artificial Intelligence Advan...
 
DESIGN AND MANUFACTURE OF CEILING BOARD USING SAWDUST AND WASTE CARTON MATERI...
DESIGN AND MANUFACTURE OF CEILING BOARD USING SAWDUST AND WASTE CARTON MATERI...DESIGN AND MANUFACTURE OF CEILING BOARD USING SAWDUST AND WASTE CARTON MATERI...
DESIGN AND MANUFACTURE OF CEILING BOARD USING SAWDUST AND WASTE CARTON MATERI...
 
Determination of Equivalent Circuit parameters and performance characteristic...
Determination of Equivalent Circuit parameters and performance characteristic...Determination of Equivalent Circuit parameters and performance characteristic...
Determination of Equivalent Circuit parameters and performance characteristic...
 
Transformers design and coooling methods
Transformers design and coooling methodsTransformers design and coooling methods
Transformers design and coooling methods
 
SCALING OF MOS CIRCUITS m .pptx
SCALING OF MOS CIRCUITS m                 .pptxSCALING OF MOS CIRCUITS m                 .pptx
SCALING OF MOS CIRCUITS m .pptx
 
4. Mosca vol I -Fisica-Tipler-5ta-Edicion-Vol-1.pdf
4. Mosca vol I -Fisica-Tipler-5ta-Edicion-Vol-1.pdf4. Mosca vol I -Fisica-Tipler-5ta-Edicion-Vol-1.pdf
4. Mosca vol I -Fisica-Tipler-5ta-Edicion-Vol-1.pdf
 
Open Channel Flow: fluid flow with a free surface
Open Channel Flow: fluid flow with a free surfaceOpen Channel Flow: fluid flow with a free surface
Open Channel Flow: fluid flow with a free surface
 
An Introduction to the Compiler Designss
An Introduction to the Compiler DesignssAn Introduction to the Compiler Designss
An Introduction to the Compiler Designss
 
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODELDEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
 
原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样
原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样
原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样
 
Asymmetrical Repulsion Magnet Motor Ratio 6-7.pdf
Asymmetrical Repulsion Magnet Motor Ratio 6-7.pdfAsymmetrical Repulsion Magnet Motor Ratio 6-7.pdf
Asymmetrical Repulsion Magnet Motor Ratio 6-7.pdf
 
一比一原版(osu毕业证书)美国俄勒冈州立大学毕业证如何办理
一比一原版(osu毕业证书)美国俄勒冈州立大学毕业证如何办理一比一原版(osu毕业证书)美国俄勒冈州立大学毕业证如何办理
一比一原版(osu毕业证书)美国俄勒冈州立大学毕业证如何办理
 
Tools & Techniques for Commissioning and Maintaining PV Systems W-Animations ...
Tools & Techniques for Commissioning and Maintaining PV Systems W-Animations ...Tools & Techniques for Commissioning and Maintaining PV Systems W-Animations ...
Tools & Techniques for Commissioning and Maintaining PV Systems W-Animations ...
 
Bituminous road construction project based learning report
Bituminous road construction project based learning reportBituminous road construction project based learning report
Bituminous road construction project based learning report
 
ITSM Integration with MuleSoft.pptx
ITSM  Integration with MuleSoft.pptxITSM  Integration with MuleSoft.pptx
ITSM Integration with MuleSoft.pptx
 
AI + Data Community Tour - Build the Next Generation of Apps with the Einstei...
AI + Data Community Tour - Build the Next Generation of Apps with the Einstei...AI + Data Community Tour - Build the Next Generation of Apps with the Einstei...
AI + Data Community Tour - Build the Next Generation of Apps with the Einstei...
 
5G Radio Network Througput Problem Analysis HCIA.pdf
5G Radio Network Througput Problem Analysis HCIA.pdf5G Radio Network Througput Problem Analysis HCIA.pdf
5G Radio Network Througput Problem Analysis HCIA.pdf
 

03 Linear Arrays Memory Representations .pdf

  • 1. Data Structures & Algorithms By Dr. Prakash Singh Tanwar Associate Professor Lovely Professional University, Punjab Topic: Linear Arrays Memory Representations
  • 2. Linear Arrays Memory Representation Basic Terminology Linear Array Memory Representation of Linear Array Traversing Array Insertion and Deletion in Array Sorting (Bubble Sort) Searching (Linear Search and Binary Search) Review Questions By:Dr. Prakash Singh Tanwar
  • 3. Basic Terminology Linear Data Structures: A data structure is said to be linear if its elements form a sequence or a linear list. Linear Array: It is a list of a finite number n of homogeneous data elements (same type of data elements) such that: • (a) the elements of the array are referenced by an index set consisting of n consecutive numbers. • (b) the elements of the array are stored respectively in successive memory locations By:Dr. Prakash Singh Tanwar
  • 4. Revision Definition Array is a group of variables of same data type having a common name. Elements of an array can be accessed through its subscript(0 to n-1) where n is the size of array. Continous memory allocation By:Dr. Prakash Singh Tanwar
  • 5. Revision: 1D Array A single- dimensional or 1-D array consists of a fixed number of elements of the same data type organized as a single linear sequence. Array declaration Syntax Ex <data_type> <array_name>[<size>]; int a[5]; char name[20]; float num[4]; By:Dr. Prakash Singh Tanwar
  • 6. Revision: 1D Array Array declaration a[0] a[1] a[2] a[3] a[4] 20 int a[5]; a[0]=9; a[1]=6; a[2]=7; a[3]=5; a[4]=20; 9 6 7 5 By:Dr. Prakash Singh Tanwar
  • 7. 1D Array Memory Representation Array declaration a[0] a[1] a[2] a[3] a[4] 20 int a[5]; a[0]=9; a[1]=6; a[2]=7; a[3]=5; a[4]=20; 9 6 7 5 1001 1003 1005 1007 1009 size of int = 2 bytes &a[0]= 1001 &a[1]= 1001+2=1003 &a[2]= 1003+2=1005 &a[3]= 1005+2=1007 &a[4]= 1007+2=1009 size of int = 2 bytes &a[0]= 1001 &a[1]= 1001+2=1003 &a[2]= 1003+2=1005 &a[3]= 1005+2=1007 &a[4]= 1007+2=1009 Note: size of int in 32 bit compiler =2 bytes Note: size of int in 32 bit compiler =2 bytes By:Dr. Prakash Singh Tanwar
  • 8. 1D Array Memory Representation Array declaration a[0] a[1] a[2] a[3] a[4] 20 int a[5]; a[0]=9; a[1]=6; a[2]=7; a[3]=5; a[4]=20; 9 6 7 5 1001 1005 1009 1013 1017 size of int = 4 bytes &a[0]= 1001 &a[1]= 1001+4=1005 &a[2]= 1005+4=1009 &a[3]= 1009+4=1013 &a[4]= 1013+4=1017 size of int = 4 bytes &a[0]= 1001 &a[1]= 1001+4=1005 &a[2]= 1005+4=1009 &a[3]= 1009+4=1013 &a[4]= 1013+4=1017 Note: size of int in 64 bit compiler =4 bytes Note: size of int in 64 bit compiler =4 bytes By:Dr. Prakash Singh Tanwar
  • 9. Q/A Are these valid statements? int a[10]; a[10]=10; a[10]=10; is not valid Because, in array a[10] we have only 10 elements from a[0] to a[9] By:Dr. Prakash Singh Tanwar
  • 10. 1D Array Memory Representation Array declaration Size of char • 1 byte Ex • Array Size 4 characters • Subscript 0 to 3 n[0] n[1] n[2] n[3] char n[4]; 5001 5002 5003 5004 size of array By:Dr. Prakash Singh Tanwar
  • 11. Basic Terminology Size / Length of Array Index of Array Upper bound and Lower bound of Array By:Dr. Prakash Singh Tanwar a[0] a[1] a[2] a[3] a[4] Size / Length of Array=5 Index of array : 0 to 4 Lower Bound Upper Bound
  • 12. Traversing Linear Array Suppose we have to count the number of element in an array or print all the elements of array. By:Dr. Prakash Singh Tanwar Algorithm 1: (Using While Loop) 1. [Initialize Counter.] Set K = LB. 2. Repeat Step 3 and 4 while K<= UB. 3. [Visit Element.] Apply PROCESS to A[K]. 4. [Increase Counter.] Set K = K+1. [End of Step 2 Loop.] 5. Exit. a[0] a[1] a[2] a[3] a[4] 20 9 6 7 5 K LB UB
  • 13. Traversing Linear Array Algorithm 2: (Using for loop) By:Dr. Prakash Singh Tanwar 1. Repeat for K = LB to UB Apply PROCESS to A[K]. [ End of Loop.] 2. Exit. a[0] a[1] a[2] a[3] a[4] 20 9 6 7 5 K LB UB
  • 14. Q/A Question.1: Find the Number of elements in an array which are greater than 25 Question 2: Find out the sum of all the two digit numbers in an array. By:Dr. Prakash Singh Tanwar a[0] a[1] a[2] a[3] a[4] 20 25 6 27 5 K LB UB
  • 15. Insertion in an Array Two types of insertion are possible: Insertion at the end of array Insertion in the middle of the array By:Dr. Prakash Singh Tanwar
  • 16. Insert an element in an Array Write a program to insert an element in an array? Where to insert? What are the current elements in the array? What value you want to insert? How many elements are there in this array? a[0] a[1] a[2] a[3] a[4] 10 20 30 By:Dr. Prakash Singh Tanwar
  • 17. Insertion in an Array Algorithm: (Insertion of an element ITEM into Kth position in a Linear Array A with N elements) By:Dr. Prakash Singh Tanwar Input: A: Array A ; N: Array A have N elements in it ITEM :item to insert ; Pos: insert item at position Pos Output: Array A with item inserted at position index ‘Pos’ Algorithm 1. [Initialize Counter.] Set I = N. 2. Repeat Steps 3 and 4 while I >= Pos. 3. [Move Ith element downward] Set A[I+1] = A[I]. 4. [Decrease Counter.] Set I = I-1. [End of Step 2 loop] 5. [Insert element.] Set A[Pos] = ITEM. 6. [Reset N] N = N+1. 7. Exit
  • 18. Insert an element in an Array Insert 15 at pos index=1, Size=3 a[0] a[1] a[2] a[3] a[4] 10 20 30 a[0] a[1] a[2] a[3] a[4] 10 20 30 30 a[0] a[1] a[2] a[3] a[4] 10 20 20 30 a[0] a[1] a[2] a[3] a[4] 10 15 20 30 A[I+1]=A[I] A[I+1]=A[I] Algorithm(for index starting from 1) 1. [Initialize Counter.] Set I = N. 2. Repeat Steps 3 and 4 while I >= Pos. 3. [Move Ith element downward] Set A[I+1] = A[I]. 4. [Decrease Counter.] Set I = I-1. [End of Step 2 loop] 5. [Insert element.] Set A[Pos] = ITEM. 6. [Reset N] N = N+1. 7. Exit I A[Pos]=ITEM Algorithm (for index starting from 0 and pos is also in the form of index) 1. [Initialize Counter.] Set I = N-1. 2. Repeat Steps 3 and 4 while I >=Pos. 3. [Move Ith element downward] Set A[I+1] = A[I]. 4. [Decrease Counter.] Set I = I-1. [End of Step 2 loop] 5. [Insert element.] Set A[Pos] = ITEM. 6. [Reset N] N = N+1. 7. Exit By:Dr. Prakash Singh Tanwar
  • 19. Insert an element in an Array int insert(int a[], int n, int key, int pos) { int i; //shift the elements to right for(i=n-1;i>=pos; i--) { a[i+1]=a[i]; } //insert the element a[pos]=key; //increase the size n++; return n; } //display array printf("n After insertion in arrayn"); for(i=0;i<size;i++) { printf("%dt",a[i]); } By:Dr. Prakash Singh Tanwar cout<<"n After insertion in array“<<endl; cout<<a[i]<<“t”; int main(void) { int arr[6] = { 10,20,30 }; int n = 3; int key=15; int pos=1; //insert element key at given pos n=insert(arr,n,key,pos); //display array display(arr,n); return 0; }
  • 20. Linear Search Write a program to search an element in an array? What are the current elements in the array? What value you want to search? By:Dr. Prakash Singh Tanwar a[0] a[1] a[2] a[3] a[4] 10 8 30 5 60
  • 21. Linear Search (un-ordered data) Input: Array a[] with size n Key to search Output : pos index of key element in the array. If not found then return -1 Algo: Start searching the element from the left most position to the end of an array. • If key element is found the return the position index • Otherwise repeat the step 1 for next position If it is not found in all position index of array then • return not found By:Dr. Prakash Singh Tanwar
  • 22. Linear Search (un-ordered data) Search key=15 By:Dr. Prakash Singh Tanwar a[0] a[1] a[2] a[3] a[4] 10 8 30 5 60 i=0 i=0 a[i]==key Not matched i=1 i=1 Not matched i=2 i=2 Not matched i=3 i=3 Not matched i=4 i=4 Not matched i=5 (out) i=5 (out) Key=15
  • 23. Linear Search (un-ordered data) Search key= 30 a[0] a[1] a[2] a[3] a[4] 10 8 30 5 60 i=0 i=0 a[i]==key a[i]==30 Not matched i=1 i=1 Not matched i=2 i=2 Matched 30 is found at pos i=2 Key=30 By:Dr. Prakash Singh Tanwar
  • 24. Linear Search (un-ordered data) // linear search for unordered data int linearSearch(int a[], int size, int key) { int i; //check each element to search the key for(i=0; i < size ; i++) { //if key is found in array if( a[i] == key ) { return i; // then return the pos i } } //if not found then return -1 return -1; } By:Dr. Prakash Singh Tanwar
  • 25. Linear Search (Sorted Array) // linear search for ordered data int linearSearch(int a[], int size, int key) { int i; //check each element to search the key for(i=0; i<size && a[i]<=key ;i++) { //if key is found in array if( a[i] == key ) { return i;// then return the pos i } } //if not found then return -1 return -1; } By:Dr. Prakash Singh Tanwar
  • 26. Linear Search (Sorted Array) Linear Search (sorted array) a[0] a[1] a[2] a[3] a[4] 10 20 30 40 50 i=0 i=0 i=1 i=1 key= 30 Key not matched 30<10 =false Key not matched 30<20 =false 10==30 20==30 i=2 i=2 Key matched 30==30 Try next element Try next element 30 found at pos i=2 By:Dr. Prakash Singh Tanwar
  • 27. Linear Search (Sorted Array) Linear Search (sorted array) a[0] a[1] a[2] a[3] a[4] 10 20 30 40 50 i=0 i=0 i=1 i=1 key= 25 Key not matched 25<10 =false Key not matched 25<20 =false 10==25 20==25 i=2 i=2 Key not matched 30==25 Try next element Try next element 25 not found in sorted array 25<30 =true Come out from loop Where the control will move from this break statement? By:Dr. Prakash Singh Tanwar
  • 28. Q/A Where the control will move from this break statement? A. Out side of loop B. come out from if C. Come out from else if D. move to increment section By:Dr. Prakash Singh Tanwar
  • 29. Linear Search (Sorted Array) // linear search for ordered data int linearSearch(int a[], int size, int key) { int i; //check each element to search the key for(i=0; i<size && a[i]<=key ;i++) { //if key is found in array if( a[i] == key ) { return i;// then return the pos i } } //if not found then return -1 return -1; } Both program works same Both program works same Opposite condition By:Dr. Prakash Singh Tanwar
  • 30. Q/A It can search sorted and unsorted elements both best case : key is found at the first element (index=0): Ω (1) worst case: key element is found at last position n (index=n-1) : O(n) By:Dr. Prakash Singh Tanwar
  • 31. Q/A What is the best case search order for linear search? A. Ω(1) B. O(n) C.O(n2) D. Ω(n) By:Dr. Prakash Singh Tanwar
  • 32. Q/A What is the best case search order for linear search? A. Ω(1) B. O(n) C.O(n2) D. Ω(n) By:Dr. Prakash Singh Tanwar
  • 33. Q/A What is the worst case search order for linear search? A. Ω(1) B. O(n) C.O(n2) D. Ω(n) By:Dr. Prakash Singh Tanwar
  • 34. Q/A What is the worst case search order for linear search? A. O(1) B. O(n) C.O(n2) D. Ω(n) By:Dr. Prakash Singh Tanwar
  • 35. Q/A Which of the program is correct for linear search algorithm? A B C D int index = -1; int i = 0; while(size > 0) { if(a[i] == key) { index = i; } if(a[i] > key)) { index = i; break; } i++; } return index; int index = -1; int i = 0; while(size > 0) { if(a[i] == key) { index = i; break; } if(a[i] > key)) { break; } i++; } return index; int index = -1; int i = 0; while(size > 0) { if(a[i] == key) { index=i; break; } if(a[i] > key)) { index = i; } i++; } return index; int index = -1; int i = 0; while(size > 0) { if(a[i] == key) { break; } if(a[i] > key)) { break; index = i; } i++; } return index; By:Dr. Prakash Singh Tanwar
  • 36. Q/A Write a program to delete an element from an array? What are the current elements in the array? What you wants to delete? How many elements are there in this array? a[0] a[1] a[2] a[3] a[4] 10 20 30 By:Dr. Prakash Singh Tanwar
  • 37. Delete Element of an array Delete 10 , Size=3 Search 10 in this array using search algo. a[0] a[1] a[2] a[3] a[4] 10 20 30 a[0] a[1] a[2] a[3] a[4] 20 20 30 a[0] a[1] a[2] a[3] a[4] 20 30 30 a[0] a[1] a[2] a[3] a[4] 20 30 Size-- a[0]=a[1] a[1]=a[2] posToDelete=0 By:Dr. Prakash Singh Tanwar
  • 38. Delete Element of an array By:Dr. Prakash Singh Tanwar Input: Pointer to an array a[], size of array, Key to delete Output: array with deleted item and size of array Step1: posToDelete =search the element in the array and get the position to delete Step 2: if key not found display message Step 3: Otherwise (if key found in array) replace the elements from posToDelete to the size of array Step 3(a): repeat the step from last element to the posToDelete Shift elements to the left hand side a[i]=a[i+1]; Step 3(b): decrease the size by one size--; Step 4 return the size
  • 39. Delete Element of an array By:Dr. Prakash Singh Tanwar cout<<“Element ” <<key<<“ not fount in array”<<endl; cout<<“Before deletion of an array”<<endl; cout<<“Which element you want to remove?”<<endl; cin>> key; cout<<“After deletion from array”<<endl;
  • 40. Binary Search a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8] a[9] 10 20 30 40 50 60 70 80 90 100 mid=(9+0)/2=4 Mid=4 Mid=4 Key=60 a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8] a[9] 10 20 30 40 50 60 70 80 90 100 Mid=(5+9)/2=7 Mid+1 Mid-1 Mid-1 Mid=(5+6)/2=5 Left=0 Left=0 Right=9 Right=9 key not found key not found a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8] a[9] 10 20 30 40 50 60 70 80 90 100 Mid=7 Mid=7 Mid+1 Mid+1 Mid-1 Mid-1 Left =mid+1 Right Right key not found key not found Mid=5 Mid=5 key found at pos 5 key found at pos 5 Right =mid-1 By:Dr. Prakash Singh Tanwar
  • 41. Binary Search Algorithm Step 1: calculate the mid position Step 2: If the key to search is found at mid then return the mid pos Step 3: If key < a[mid] value, then it is in left side. so, recursively find it in left side from left to mid - 1 Step 4: otherwise , then it is in right side. so, recursively find it in right side i.e. from mid + 1 to right Step 5: if it is not found in left and right then return -1 (not found) By:Dr. Prakash Singh Tanwar
  • 42. Binary Search cout<<“key is not found in array” <<endl; cout<<“key is found at index ”<<pos<<endl; By:Dr. Prakash Singh Tanwar
  • 43. Binary Search cout<<“key is not found in array” <<endl; cout<<“key is found at index ”<<pos<<endl; By:Dr. Prakash Singh Tanwar
  • 44. Binary Search-Algo-2 Algorithm 1. BINARY ( DATA, LB, UB, ITEM, LOC ) 2. [Initialize Segment Variables] Set BEG = LB, END = UB and MID = INT ((BEG+END)/2). 3. Repeat Steps 3 and 4 while BEG <= END and DATA [MID] != ITEM. 4. If ITEM < DATA[MID], then: Set END = MID - 1. Else: Set BEG = MID + 1. [End of if Structure.] 5. Set MID = INT ((BEG+END)/2). [End of Step 2 Loop.] 6. If DATA [MID] = ITEM, then: Set LOC= MID Else: Set LOC = NULL. [End of if structure.] 7. Exit. By:Dr. Prakash Singh Tanwar
  • 45. Binary Search Binary search order is O(log n ) If n=1024 then it will take max. log2(1024)=log2(210) =10 steps 1024512256128643216 8421 By:Dr. Prakash Singh Tanwar
  • 46. Q/A If there are 1000 elements in an array. Then how many maximum steps are needed to search an element in an array using binary search ? A. 9 B. 1000 C. 999 D. 10 By:Dr. Prakash Singh Tanwar
  • 47. Limitations of Binary Search Although the complexity of Binary Search is O (log n), it has some limitations: The list must be sorted One must have direct access to the middle element in any sublist. By:Dr. Prakash Singh Tanwar