2-Dimensional Arrays and Searching
2-Dimensional Arrays and Searching
And searching
A[0,1]
Student 1
Test1 56 55 44
Test2 44 78 34
A[1,1]
2 3
Suppose a is a 2-dimensional array. The first dimension of A Contains the index set 1---m, with LB=1 and UB=m and second with LB=1 and UB=n. the length of a dimension is the number of integers in its index set. The pair of lengths m x n is called the size of the array
1,3
2,1 2,2 2,3 3,1 3,2 3,3
1,2
2,2 3,2 1,3 2,3 3,3
Searching
Searching refers to the operation of finding the location LOC of ITEM in DATA, or printing some message that item does not appear there. The search is said to be successful if item does appear in DATA and unsuccessful otherwise Two techniques for searching the data. Linear Search
Binary Search
The algorithm one chooses generally depends on organization of the array elements. If the elements are in random order, then one must use linear search technique and if the array elements are sorted then it is preferable to use binary search technique
Linear Search:
1) 2) Set i=0
Algo(Linear Search)
3)
If(a[i]=item) then
Set loc=I Exit //element found at location I
4) Set i=i+1 [end loop] 5) Set loc=-1 //element not found 6) exit
In the best case the item may occur at first position. In this case the search operation terminates in success with just one comparison. In worst case i.e either the item is present at last position or missing from the array the search terminates in a failure or either n comparisons.
Binary Search
Prerequisite for applying this technique is that the data should be in sorted order i.e in increasing numerical order for example telephone directory .
4) Set MID:=INT((BEG+END)/2)
5)If DATA[MID] =Item then Set LOC:= MID Else Set LOC:=NULL
6) EXIT
10
Search :30
3,11,22,30,40,44,55,60,66,77,
Mid=INT((1+10)/2)=5
A[5]=40
Item<40
Set end=mid-1(5-1=4)
11
2)One must have direct access to the middle element in any sub list.
12