Example Code

Bubble Sort in LabVIEW

Products and Environment

This section reflects the products and operating system used to create the example.

To download NI software, including the products shown below, visit ni.com/downloads.

    Software

  • LabVIEW

    Operating System

  • Windows

    Programming Language

  • LabVIEW G

Code and Documents

Attachment

Description

This is the LabVIEW implementation of the Bubble sort Algorithm. Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order.

 

Take an array of numbers " 5 1 4 2 8", and sort the array from lowest number to greatest number using bubble sort. In each step, elements written in bold are being compared. Three passes will be required;

First Pass
( 5 1 4 2 8 ) → ( 1 5 4 2 8 ), Here, algorithm compares the first two elements, and swaps since 5 > 1.
( 1 5 4 2 8 ) → ( 1 4 5 2 8 ), Swap since 5 > 4
( 1 4 5 2 8 ) → ( 1 4 2 5 8 ), Swap since 5 > 2
( 1 4 2 5 8 ) → ( 1 4 2 5 8 ), Now, since these elements are already in order (8 > 5), algorithm does not swap them.
Second Pass
( 1 4 2 5 8 ) → ( 1 4 2 5 8 )
( 1 4 2 5 8 ) → ( 1 2 4 5 8 ), Swap since 4 > 2
( 1 2 4 5 8 ) → ( 1 2 4 5 8 )
( 1 2 4 5 8 ) → ( 1 2 4 5 8 )

Now, the array is already sorted, but the algorithm does not know if it is completed. The algorithm needs one whole pass without any swap to know it is sorted.

Third Pass
( 1 2 4 5 8 ) → ( 1 2 4 5 8 )
( 1 2 4 5 8 ) → ( 1 2 4 5 8 )
( 1 2 4 5 8 ) → ( 1 2 4 5 8 )
( 1 2 4 5 8 ) → ( 1 2 4 5 8 )

This is how the algorithm works and you can visually see this in the code attached below.

How to Use

Kindly follow the steps in order to visualize the Bubble sort in LabVIEW.

 

 

1. Download the VI and open it in LabVIEW.

2. Add elements onto the Array input (Size of the array is optional you can have as many array elements as you want).

3. After completing the data entry hit the Run arrow button.

4. Simultaneously you can see how array elements are SWAPPED and how much Passes it took for the algorithm to sort all the elements of the array.

Related Links

For a better understanding of the Bubble Sort Algorithm kindly refer to the Link below,

 

https://en.wikipedia.org/wiki/Bubble_sort

Example code from the Example Code Exchange in the NI Community is licensed with the MIT license.