Assembly Program to find Second Smallest Number in an Array


This program has a byte ARRAY, a variable called the SMALLEST and another variable called SECOND_SMALEST. The program will find the smallest integer in the ARRAY and will assign it to the variable SMALLEST and then find the second smallest number and assign it to the variable SECOND_SMALLEST.

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

After finding the smallest number in array the program moves on to find the second-smallest number. For this, program checks for every number if its smaller than the value assigned to SECOND_SMALLEST and greater than the value assigned to SMALLEST then update SECOND_SMALLEST 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
SMALLEST DB ?
SECOND_SMALLEST DB ?
.CODE
MAIN PROC
    
    MOV AX, @DATA
    MOV DS, AX
    
    MOV BX, 0
    
    MOV AL, ARRAY[BX]
    
    MOV SMALLEST, AL
    
    COMPARE_1:
    
    INC BX
    
    CMP BX, 10
    
    JE UPDATED_SMALLEST
    
    MOV AL, ARRAY[BX]
    
    CMP AL, SMALLEST
    
    JL UPDATE_SMALLEST
    
    JMP COMPARE_1
    
    UPDATE_SMALLEST:
    
    MOV SMALLEST, AL
    
    JMP COMPARE_1
    
    UPDATED_SMALLEST:
    
    MOV BX, 0
    
    FIND_SECOND_SMALLEST:
    
    MOV AL, ARRAY[BX]
    
    CMP AL, SMALLEST
    
    JE SPECIAL_CASE
    
    MOV SECOND_SMALLEST, AL
    
    JMP COMPARE_2
    
    SPECIAL_CASE:
    
    INC BX
    
    JMP FIND_SECOND_SMALLEST    
    
    COMPARE_2:
    
    INC BX
    
    CMP BX, 10
    
    JE EXIT
    
    MOV AL, ARRAY[BX]
    
    CMP AL, SECOND_SMALLEST
    
    JL UPDATE_SECOND_SMALLEST
    
    JMP COMPARE_2
    
    UPDATE_SECOND_SMALLEST:
    
    CMP AL, SMALLEST
    
    JE COMPARE_2
    
    MOV SECOND_SMALLEST, AL
    
    JMP COMPARE_2
    
    EXIT:
    
    MAIN ENDP
END MAIN

Output:


No comments