Mix (C++ and Assembly) Program to Sort Numbers in Ascending Order

This post demonstrates how to sort an array of integers using inline assembly in C++. Here, we perform sorting in ascending order by comparing and swapping adjacent elements using embedded assembly 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
                jl 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 as temporary variables to hold values during the sorting comparisons.

User Input

The user is prompted to input 5 integers which are stored in the array a.

Inline Assembly for Sorting (Ascending Order)

  • mov ax, x → Loads the current element x into register AX.
  • mov bx, y → Loads the next element y into register BX.
  • cmp ax, bx → Compares the values in AX and BX.
  • jl nxt → If AX < BX, skip the swap (since already in order).
  • Otherwise, values in x and y are swapped using CX as a temporary register.

This comparison and potential swap ensures that smaller elements bubble to the front of the array.

Output Display

After all passes, the sorted array is printed in ascending order using cout.


Output

 Enter 5 Numbers:10
5
48
12
34
 Sorted Array:5 10 12 34 48

Output Explanation

The program sorts the numbers 10, 5, 48, 12, 34 into ascending order. After comparing and swapping where needed using inline assembly, the sorted result is: 5 10 12 34 48.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.