Friday, 24 June 2011

Bubble Sort algorithm




Nice bubble sort example from Kevin, I've made a simpler version below
/*
demonstrates a bubble sort algorithm, a variety of 'comparison sort'.
involves repeatedly stepping through the list to be sorted, comparing each pair of adjacent
items and swapping them if they are in the wrong order. The pass through the list is
repeated until no swaps are needed, which indicates that the list is sorted.
The algorithm gets its name from the way smaller elements "bubble" to the top of the list
adapted from Kevin:
http://processing.org/discourse/yabb/YaBB.cgi?board=Programs;action=display;num=1059766998


**/

//NASTY BLOG DOESNT WANT TO DISPLAY CODE PROPERLY

void bubbleSort(int array[])
{
int i, j;
boolean sorted = false;

// while the array isn't sorted
while (!sorted) {
sorted = true;
// loop through array
for (i=0;i array[i+1]) {
// swap values
j = array[i];
array[i] = array[i+1];
array[i+1] = j;
//println(array);
// trigger's been hit, array isn't sorted.
sorted = false;
}
}
}
}






No comments:

Post a Comment