Sei sulla pagina 1di 4

Data Structures

LAB SESSION 3 BS(SE) 2018

Department of CS and IT

Object: To implement the algorithm for traversing an array.

Traversing: Visiting each element exactly once.

Algorithm: Traversing an array.

LA is a linear array with lower bound LB and upper bound UB. This algorithm traverses LA applying and
operation PROCESS to each element of LA.

Step1: [Initialize counter.] Set K: = LB

Step2: Repeat steps 3 and 4 while K  UB.

Step3: [visit element.] Apply PROCESS to LA [K]

Step4: [Increase counter] Set K: = K + 1

Step5: [End of step2 loop.]

Step6: Exit.
CSC 2051/ CSC 2051
Data Structures
LAB SESSION 3

Object: To implement an algorithm for finding the maximum number in an array.

Algorithm: To find largest element in array


A nonempty array DATA with N numerical values is given. This algorithm finds the location LOC and the
value MAX of the largest element of DATA. The variable K is used as counter.

Step 1: [Initialize] Set K := 1, LOC := 1 and MAX := DATA[1].

Step 2: [Increment counter] Set K:= K + 1

Step 3: [Test counter] If K>N, then:

Write LOC, MAX, and Exit.

Step 4: [Compare and update] If MAX < DATA[K], then:

Set LOC:= K and MAX := DATA[K]

Step 5 : [Repeat loop] Go to step2.

2
CSC 2051/ CSC 2051
Data Structures
LAB SESSION 3
Step 6: Exit

Object: Insertion in an array


Algorithm: (Inserting into Linear Array) INSERT (LA, N, K, ITEM)
Here LA is a linear array with N elements and K is a positive integer such that K<=N. The algorithm
inserts an element ITEM into the Kth position in LA.

1. [Initialize counter] Set J: = N.

2. Repeat Steps 3 and 4 while j >= k;

3. [Move jth element downward.]

Set LA [J + 1]: =LA [J].

4. [Decrease counter] Set J: = J-1

[End of step 2 loop]

5. [Insert element] Set LA [K]:=ITEM.

6. [Reset N] Set N:=N+1

7. EXIT

Exercise:
1. Implement the above algorithms in java/python Language. Use proper indentation and comments in
your code.

2. Test your programs with different values and show the output.

Program : Traversing
Input string Expected output Actual Output
Student
Jinnah University

Program : Maximum Number


Input Expected output Actual Output
1,3,85,9,0,6,10
90,21,65,21,1,9,11

3
CSC 2051/ CSC 2051
Data Structures
LAB SESSION 3
3. Test Run with trace.

K J J>=K LA [J + 1]=LA [J] J=J-1

Potrebbero piacerti anche