You might find me posting implementations of algorithms, data structures and the like around here. Working on such is how my free time gets spent.
My ultimate aim in the future is to rip the Linux kernel apart, critique the code, it should probably be fun to also get my changes merged into the ultimate open source project there is out there.
Anyway, to start with, here is my implementation of the worst sorting algorithm there possibly is out there, bubble sort.
Any comments, critique or basically any sort of input to this thread would be much appreciated.
Here we go, cheers!
#include <iostream>
void BubbleSort(size_t length/* size of the array */, int *arr /* array itself */, bool order /* sorting order, ascending or descending */)
{
for(size_t i = 0; i < length; i++)
{
for (size_t j = 0; j < length; j++)
{
/* sort according to the order */
if ( order )
{
if (arr[j] > arr[i])
{
/* swap */
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
else
{
else if (arr[j] < arr[i])
{
int temp = arr[j];
arr[j] = arr[i]
arr[i] = temp;
}
}
}
}
return;
}
Thanks in advance! 
PS: It just occurred to me that the board does not handle code in the best way there is making it a lot more harder to read.
You might want to view the code as it appears in a text editor [img src="https://imgur.com/DCqfmGv"> here
Okay, whatever, BBCode seemed to fix it.
A more recent version of the code, presumably the correct code:
#include <stdio.h>
#include <stdbool.h>
void BubbleSort(int *arr /* array itself */, size_t length, bool order /* sorting order, ascending or descending */)
{
/* do not take chances with the compiler */
if ( order )
{
for(size_t i = 0; i < length; i++)
{
for(size_t j = 1; j < length - 1; j++)
{
if (arr[j - 1] < arr[ j ])
{
int temp = arr [ j ];
arr[ j ] = arr[j - 1];
arr[j - 1] = temp;
}
}
}
}
else
{
for(size_t i = 0; i < length; i++)
{
for(size_t j = 1; j < length; j++)
{
if (arr[j - 1] > arr[ j ])
{
int temp = arr [ j ];
arr[ j ] = arr[j - 1];
arr[j - 1] = temp;
}
}
}
}
}
int main(int argc, char *argv)
{
const int ArrayLength = 50;
int arr[50] = {
0x40, 0x50, 0x8, 0x31, 0x6, 0x19, 0x5, 0x40, 0x30, 0x31,
0x41, 0x32, 0x41, 0x20, 0x36, 0x46, 0x31, 0x20, 0xff, 0x12,
0x45, 0xe, 0xa, 0x3e, 0x22, 0x43, 0x32, 0x41, 0x45, 0x36,
0xfe, 0x5a, 0xef, 0x3d, 0x23, 0x34, 0xf3, 0x22, 0x31, 0x5a,
0xff, 0x3e, 0x5f, 0x88, 0x100, 0x34, 0x45, 0x21, 0xfd, 0x35
};
BubbleSort(arr, ArrayLength, true)
for(int i = 0; i < ArrayLength; /* i++ */)
{
for (int j = 0; j < 10; j++)
{
fprintf(stdout, "0x%x ", arr[i + j])
}
i+=10;
fprintf(stdout, "\n")
}
return 0;
}
|