|
Author |
Topic: Bubblesort (Read 955 times) |
|
kevin
|
Bubblesort
« on: Aug 1st, 2003, 9:43pm » |
|
Thanks to toxi for the help on the syntax forum. I've achived what I wanted. A simple bubblesort animation. Code:// BubbleSort // Create unsorted array int[] array = { 7, 10, 6, 3, 8, 1, 14, 2, 9, 4, 5, 13, 18, 16, 17, 15, 12, 11 }; void setup() { size(200,200); background(100,24,020); framerate(4); println("Program Started"); } void loop() { // Draw the array drawArray(array, 75, 50); // If the mouse is pressed sort they array if (mousePressed == true) { bubbleSortInc(array); } } // Incremental bubble sort. // Note, there should be a check for when the array is sorted // I'll leave that for now though. void bubbleSortInc(int array[]) { int i, j; boolean sorted = false; // loop through array for (i=0;i<array.length-1;i++) { if (array[i] > array[i+1]) { // swap values j = array[i]; array[i] = array[i+1]; array[i+1] = j; } } } // Print the array for debugging purposes void printArray(int array[]) { int i=0; for (i=0;i<array.length;i++) { print(array[i] + ","); } println(); } // Drawy the array to the screen void drawArray(int array[], int x, int y) { int lineLength = 10; // Width of the bars int lineThickness = 5; int i=0; // loop through array for (i=0;i<array.length;i++) { lineLength = array[i]*5; fill (0); noStroke(); rect(x, y+(lineThickness*i), lineLength, lineThickness-1); } } |
| Here's the basic bubblesort function on it's own. Code: 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.length-1;i++) { if (array[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; } } } } |
| Now to have some fun with it, watch this space...
|
« Last Edit: Aug 1st, 2003, 9:43pm by kevin » |
|
|
|
|
|