Hi,
I am trying to teach my son the difference between the sorting algorithms therefore I did a small program on Arduino IDE that I am running on an Arduino NANO. Besides sorting I am calculating as well the numbers of cycles and the time needed by the algorithm needed to sort the vector. At the end I send the results on the serial port.
The code is:
// Sorting algorithm reverse
int a[200];
int i,j,temp,cycle;
unsigned long micro1,micro2;
void setup() {
Serial.begin (57600);
}
void loop()
{
randomSeed(micros());
for (i=0;i<200;i++)
a = random(-9999,9999);
cycle=1;
micro1 = micros();
for (i=0;i<199;i++)
{
- for(j=199;j>i;j--)*
- {*
_ if (a*>a[j])_
_ {_
_ temp = a ;
a = a [j];
a [j] = temp;
}
cycle++;
}
}
micro2 = micros();
for (i=0;i<200;i++)
{
Serial.print("a[");
Serial.print(i);
Serial.print("]=");_
_Serial.println(a);
}
Serial.print("Sort Duration: ");
Serial.print(micro2-micro1);
Serial.println("uS");
Serial.print("Cycles: ");
Serial.println(cycle);
delay (1000);
}
and the result of the sorting algorithm is:
.....
a[195]=9319
a[196]=9516
a[197]=9657
a[198]=9794
a[199]=9854
Sort Duration: 24548uS
Cycles: 19901
Now, the strange thing. If I modify a little bit the algorithm and in the sense that in the second iteration loop instead of going from the last element to the first one, i go from the first to the last, although the number of cycles required by the algorithm to sort the vector remains the same, the duration is almost double. i do not understand why. It does not make any sense for me. Below the modified algorithm and the results.
// Sorting algorithm direct*
int a[200];
int i,j,temp,cycle;
unsigned long micro1,micro2;
void setup() {
Serial.begin (57600);
}
void loop()
{
randomSeed(micros());
for (i=0;i<200;i++)
a = random(-9999,9999);
cycle=1;
micro1 = micros();
for (i=0;i<199;i++)
{
for(j=i+1;j<200;j++)
* {
if (a>a[j])
{
temp = a ;
a = a [j];
a [j] = temp;
}
cycle++;
}
}
micro2 = micros();
for (i=0;i<200;i++)
{
Serial.print("a[");
Serial.print(i);
Serial.print("]=");_
_Serial.println(a);
}
Serial.print("Sort Duration: ");
Serial.print(micro2-micro1);
Serial.println("uS");
Serial.print("Cycles: ");
Serial.println(cycle);
delay (1000);
}
.....*
a[197]=9783
a[198]=9827
a[199]=9959
Sort Duration: 38388uS
Cycles: 19901
Any idea?
Many thanks.
Florin_