Assembly Program to find Second Largest Number in an Array


This program has a byte ARRAY, a variable called the LARGEST and another variable called SECOND_LARGEST. The program will find the largest integer in the ARRAY and will assign it to the variable LARGEST and then find the second largest number and assign it to the variable SECOND_LARGEST.

The basic logic in the program is that we assign the first element of the array to the LARGEST and start iteration from element 2. If the element 2 is larger than the value assigned to LARGEST, we update LARGEST otherwise go to element 3 and compare LARGEST with element 3 and so on.

After finding the largest number in array the program moves on to find the second-largest number. For this, program checks for every number if its larger than the value assigned to SECOND_LARGEST and lesser than the value assigned to LARGEST then update SECOND_LARGEST otherwise moves on.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
.MODEL SMALL
.STACK 100H
.DATA
ARRAY DB 100, 32, 98, 21, 13, 68, 38, 25, 56, 12
LARGEST DB ?
SECOND_LARGEST DB ?
.CODE
MAIN PROC
    
    MOV AX, @DATA
    MOV DS, AX
    
    MOV BX, 0
    
    MOV AL, ARRAY[BX]
    
    MOV LARGEST, AL
    
    COMPARE_1:
    
    INC BX
    
    CMP BX, 10
    
    JE UPDATED_LARGEST
    
    MOV AL, ARRAY[BX]
    
    CMP AL, LARGEST
    
    JG UPDATE_LARGEST
    
    JMP COMPARE_1
    
    UPDATE_LARGEST:
    
    MOV LARGEST, AL
    
    JMP COMPARE_1
    
    UPDATED_LARGEST:
    
    MOV BX, 0
    
    FIND_SECOND_LARGEST:
    
    MOV AL, ARRAY[BX]
    
    CMP AL, LARGEST
    
    JE SPECIAL_CASE
    
    MOV SECOND_LARGEST, AL
    
    JMP COMPARE_2
    
    SPECIAL_CASE:
    
    INC BX
    
    JMP FIND_SECOND_LARGEST    
    
    COMPARE_2:
    
    INC BX
    
    CMP BX, 10
    
    JE EXIT
    
    MOV AL, ARRAY[BX]
    
    CMP AL, SECOND_LARGEST
    
    JG UPDATE_SECOND_LARGEST
    
    JMP COMPARE_2
    
    UPDATE_SECOND_LARGEST:
    
    CMP AL, LARGEST
    
    JE COMPARE_2
    
    MOV SECOND_LARGEST, AL
    
    JMP COMPARE_2
    
    EXIT:
    
    MAIN ENDP
END MAIN

Output:


No comments