vbnet
Communicating with the Arduino in VB.NET (Serial Communication)
May 3, 2016
ard
Comparing various types of Ardunio
May 3, 2016
Show all

Bubble Sorting with a Arduino/C++ Application

bubble

One of the first things to learn in programming is how to sort numbers. It is an easy task in most high-level programming languages as functions exist to do this. But how do they work? What if you’re working with a platform that doesn’t have such functions? We can sort an array of integers with what’s known a the Bubble Sort Algorithm.

Bubble sort, sometimes referred to as sinking sort, is a simple sorting algorithm that repeatedly steps through the list to be sorted, compares each pair of adjacent items and swaps them if they are in the wrong order.

Below is code that is designed to work on an Arduino, it will sort an array of integers. Note that this isn’t the fastest way to sort data, especially large amounts of it. But it does work quite effectively.

int sortValues[13] = { 2, 7, 4, 6, 5, 3, 8, 10, 9, 11, 14, 12, 13 }; 

void setup(){
  Serial.begin(9600);
}

void loop() {
  sort(sortValues,13); //Pass in the values and the size.

  Serial.print("Sorted Array: ");
  for(int i=0; i<13; i++) {
     Serial.print(sortValues[i]); 
     Serial.print(",");
  }
  Serial.println("");
  Serial.print("Max Number: ");
  Serial.print(sortValues[12]);
  Serial.println("");
  Serial.print("Min Number: ");
  Serial.print(sortValues[0]);
  Serial.println("");
  delay(10000); //Make sure we have enough time to see the output before starting the demo again.
}

void sort(int a[], int size) {
    for(int i=0; i<(size-1); i++) {
        for(int o=0; o<(size-(i+1)); o++) {
                if(a[o] > a[o+1]) {
                    int t = a[o];
                    a[o] = a[o+1];
                    a[o+1] = t;
                }
        }
    }
}

You can see on the basic diagram below how the Bubble Sort Algorithm works and how it steps through the array comparing elements to each other.

BubbleSort

The above code has been tested on an Arduino and it will work in C++ and on most other Microcontrollers.

Leave a Reply

Your email address will not be published. Required fields are marked *