## Saturday, May 29, 2010

### Bubble Sort

Bubble sort

How it works;
Basically bubble sort works by stepping through the data a swapping the current and next data items if they are out of order.

Properties;
Best case and worst case speed are both O(n^2)
Memory is 1 (the temp swap location)

//compile with g++
#include <iostream>
#include <iomanip>
using namespace std;

void print(int data[], int size);

void bubblesort(int data[], int size)
{
bool change = true;
int tmp;
while(change)
{
change = false;
for(int i = 0;i < size-1;i++)
if(data[i] > data[i+1])
{
tmp = data[i];
data[i] = data[i+1];
data[i+1] = tmp;
change = true;
}
}
}

//test
#define SIZE 20
#define SCRAMBLE(x, y) ((0xa57b & ~y) + ((0x3829 & x) << 1))

bool check(int data[], int size)
{
for(int i = 1; i < size; i++)
if(data[i] < data[i-1])
{
cout << "FAIL!" << endl;
return false;
}
cout << "PASS" << endl;
return true;
}

void print(int data[], int size)
{
for(int i = 0; i < size; i++)
cout << setw(5) << data[i] << " ";
cout << endl;
}

bool test(int data[], int size)
{
print(data, SIZE);
bubblesort(data,SIZE);
print(data, SIZE);
return check(data, SIZE);
}

int main()
{
int data[SIZE];
bool pass = true;

//easy data
data[0] = 1;
for(int i = 0; i < SIZE; i++)
data[i] = SIZE - i;
pass &= test(data, SIZE);

//semi repeated data
data[0] = 1;
for(int i = 0; i < SIZE; i++)
data[i] = SCRAMBLE(i, data[i-1]);
pass &= test(data, SIZE);

//the sort killer!
for(int i = 0; i < SIZE; i++)
data[i] = 5;
pass &= test(data, SIZE);

//and some randoms to catch anything i missed
srand ( time(NULL) );

for(int j = 0; j < 100; j++)
{
for(int i = 0; i < SIZE; i++)
data[i] = (int)((float)(j+1)*((float)rand()/(float)RAND_MAX));
pass &= test(data, SIZE);
}

if(pass)
cout << "ALL PASSED" << endl;
else
cout << "FAILED" << endl;
}