Arrays
Linear Arrays A linear array is a list of a finite number n of homogeneous data elements (i.e., data elements of the same type) such that: The elements of the array are referenced respectively by an index set consisting of n consecutive numbers. The elements of the array are stored respectively in successive memory locations. The length or the number of data elements of the array can be obtained from the index set by the following formula: Length = UB - LB + 1
Representation of Linear Arrays in Memory Let LA be a linear array in the memory of the computer. The computer calculates the address of kth Element of the array by the following formula: LOC(LA[K]) = Base(LA) + w(K – LB) Here, W is the number of words per memory cell for the array LA. 1000 1001 1002 . LA[1] LA[2] LA[3] .
Traversing a linear array Algorithm 4.1: Set K := LB Repeat step 3 and 4 while K <= UB Apply PROCESS to LA[K] Set K := K + 1 Exit
Inserting into a linear array Algorithm 4.2: INSERT( LA, N, K, ITEM) Set J := N Repeat Steps 3 and 4 while J >= K Set LA[J+1] := LA[J] Set J := J – 1 Set LA[K] := ITEM Set N := N + 1 Exit
Deleting From a Linear Array Algorithm 4.3: DELETE( LA, N, K, ITEM) Set ITEM := LA[K] Repeat for J := K to N – 1 Set LA[J] := LA[J+1] 3. Set N := N - 1 4. Exit
Searching Searching refers to the operation of finding an item from a list of items based on some key value. Two Searching Methods Linear Search Binary Search
Algorithm: Linear-Search (LA, N, Key) A linear search is a technique for finding a particular value in a unsorted or sorted list. Search each item of list using key value, one at a time, until finding the item from the list. Algorithm: Linear-Search (LA, N, Key) Set k := 1 and Loc := 0 Repeat Steps 3 and 4 while k <= N If Key = LA[k], then Set Loc := k, print: Loc and exit. Set k := k+1 If Loc = 0 then Write: Item is not in List Exit Here L - The list of data items N – Total no. of items in L Key – Item to be searched.
Example of Linear Search List : 10, 6, 222, 44, 55, 77, 24 Key: 55 Steps: 6 222 44 55 77 24 K=1 10 222 44 55 77 24 K=2 10 6 44 55 77 24 K=3 10 6 222 55 77 24 K=4 10 6 222 44 77 24 K=5 So, Item 55 is in position 5. 55 10 6 222 44
Complexity Analysis of Linear Search Worst Case The worst case occurs when Item is the last element in the List or is not in the List. So, C(n) = n = O(n). (2) Average Case The average case occurs when the availability of the Item in the List is equally likely to occur at any position in the List. So, C(n) = = = 0(n)