This post demonstrates how to sort an array of integers using inline assembly in C++. We use basic comparison and swap logic in assembly embedded within a C++ program.
#include<iostream.h>
#include<conio.h>
void main()
{
int a[5], x, y;
int i, j;
cout << "\n Enter 5 Numbers:";
for(i = 0; i < 5; i++)
{
cin >> a[i];
}
//Sorting
for(i = 0; i < 4; i++)
{
for(j = 0; j < 4; j++)
{
x = a[j];
y = a[j + 1];
asm {
mov ax, x
mov bx, y
cmp ax, bx
jge nxt
mov cx, ax
mov ax, bx
mov bx, cx
mov x, ax
mov y, bx
}
nxt:
a[j] = x;
a[j + 1] = y;
}
}
cout << "\n Sorted Array:";
for(i = 0; i < 5; i++)
cout << a[i] << " ";
getch();
}
Understanding the Code
Variable Declarations
int a[5], x, y;
→ a
is the array to be sorted. x
and y
are used for temporary storage during comparisons and swaps.
User Input
The user is prompted to enter 5 integer values which are stored in the array a
.
Inline Assembly for Sorting
The program performs a bubble sort using nested loops. Inline assembly is used to compare and swap adjacent elements:
mov ax, x
→ Load value of x into register AX.mov bx, y
→ Load value of y into register BX.cmp ax, bx
→ Compare AX and BX.jge nxt
→ Jump if AX ≥ BX (i.e., no swap needed).- If AX < BX, values are swapped using CX as temporary storage.
- Updated values of x and y are written back to the array.
Output Display
Once sorting is complete, the sorted array is displayed in descending order.
Output
Enter 5 Numbers:10
5
20
15
36
Sorted Array:36 20 15 10 5
After entering the numbers 10, 5, 20, 15, 36
, the program uses inline assembly to sort the array in descending order using a bubble sort mechanism. Here’s how the values change:
- On the first iteration, the highest number
36
bubbles to the front. - Subsequent iterations continue comparing and swapping adjacent elements, placing larger numbers earlier in the array.
- Finally, the sorted array is:
36 20 15 10 5
.