# Sorting Values in RobotC

I’m trying to implement a median filter on my robot, and in order to do so I need to sort 5 values and retrieve the middle one. Does anyone know how I can do this?

Probably a bit over the top just for this but the library that BNS wrote has this functionality.

For sorting a small number of values you can use a simple bubble sort algorithm.

Thank you!
I was aware of this library, but I like to learn how to do things myself. There would be no library if they didn’t learn how to do the things in it.

So try and write a simple bubble sort in robotc. If you have problems continue to post in this thread and I will give you some more help.

``````bool Solved = false;
typedef struct{
char Sort[3];
} Sonar;

Sonar old;
Sonar new;

{
old.Sort[0] = 1;
old.Sort[1] = 4;
old.Sort[2] = 3;

while(!Solved)
{
if (old.Sort[0] > old.Sort[1])
new.Sort[1] = old.Sort[1];
new.Sort[0] = old.Sort[0];
old.Sort[0] = new.Sort[1];
old.Sort[1] = new.Sort[0];
if (old.Sort[1] > old.Sort[2])
new.Sort[2] = old.Sort[2];
new.Sort[1] = old.Sort[1];
old.Sort[2] = new.Sort[1];
old.Sort[1] = new.Sort[2];
if ((old.Sort[0] < old.Sort[1]) && (old.Sort[1] < old.Sort[2]))
Solved = true;

writeDebugStream("%i,%i,%i,",old.Sort[0],old.Sort[1],old.Sort[2]);
writeDebugStreamLine("");
}

}
``````

This is the code I am using and it is not working. What is wrong?

Well, the problem is that when using a statement like this.

``````
if (old.Sort[0] > old.Sort[1])
new.Sort[1] = old.Sort[1];
new.Sort[0] = old.Sort[0];
old.Sort[0] = new.Sort[1];
old.Sort[1] = new.Sort[0];

``````

Only the first statement will execute if the if statement is true, I think you probably meant to write this.

``````
if (old.Sort[0] > old.Sort[1])
{
new.Sort[1] = old.Sort[1];
new.Sort[0] = old.Sort[0];
old.Sort[0] = new.Sort[1];
old.Sort[1] = new.Sort[0];
}

``````

It’s a rather complex way of swapping those two values. Here is an example of a bubble sort (completely unoptimized) in ROBOTC.

``````
void
bubbleSort(  int *a, int length )
{
int i, tmp;
bool swapped = false;

do
{
swapped = false;

for(i=1;i<length;i++)
{
if( a* > a* )
{
tmp = a*;
a* = a*;
a* = tmp;

swapped = true;
}
}
} while(swapped);
}

{
int  a] = {4, 1, 3, 7, 2, 0};
int  i, len;

len = (sizeof(a)/sizeof(int));

for(i=0;i<len;i++)
writeDebugStream("%d ", a*);
writeDebugStreamLine("" );

bubbleSort( a, len );

for(i=0;i<len;i++)
writeDebugStream("%d ", a*);
writeDebugStreamLine("" );
}
``````

Notice how I use a temporary variable to swap the two values.********

I agree with jpearman on using the bubble sort algorithm for sorting the small data size. However, only use bubble sort when dealing with small input sizes because the algorithm’s run-time grows exponentially as you get more values – causing your software to be inefficient and slow – in this case use the merge sort algorithm as it has a way faster average run-time of O(n lg n), while bubble has a run-time of average O(n^2).