#### Howdy, Stranger!

We are about to switch to a new forum software. Until then we have removed the registration on this forum.

# BubbleSort

edited February 2017

i want to order by a diameter those bubbles but i doesnt work someone help me? here is my codes

``````var bubbleArray = [];
var sortedA = [];
var distance = 0;
var y = 0;

function setup() {
createCanvas(640, 450);
for (var i = 0; i < 5; i++) {
bubbleArray.push(new createBubble());
distance = distance + 50;
}
}

function draw() {
background(200);

noLoop();
for(var i = 0; i < bubbleSort().length; i++) {
bubbleSort()[i].display();
}
}

function createBubble() {
this.x = 30 + distance;
this.y = 40;
this.diameter = random(20, 50) + 2;
this.display = function() {
ellipse(this.x,this.y,this.diameter,this.diameter);
}
}

function bubbleSort() {
var temp = 0;
for(var i = 0; i < bubbleArray.length; i++) {
for(var j = 0; j < bubbleArray.length - 1; j++ ) {
if (bubbleArray[j].diameter > bubbleArray[j + 1].diameter) {
temp = bubbleArray[j + 1].x;
bubbleArray[j + 1].x = bubbleArray[j].x;
bubbleArray[j].x = temp;
}
}
}
return bubbleArray;
}
``````
Tagged:

• Is line 19 call as many times as the size of the array? Why not to store the returning object in another variable? And since bubbleArray is global, you could use it in your draw instead.

Kf

• You need to call the functions

• ``````for(var i = 0; i < bubbleSort().length; i++) {
``````

how many times does this loop run?

• The algorithm used in the method bubbleSort will sort the array but it certainly isn't a Bubble Sort.

• why not?

it's trundling through the array swapping adjacent entries based on size.

it does this inefficiently - it always does the entire array despite the fact parts of it will be sorted by earlier iterations, it's not checking to see whether the list is already sorted - but these are just optimisations...

• Because the bubble sort algorithm includes these opimisations as standard so without them it is not a bubble sort or even an inefficient bubble sort.

• potato / potato, tomato / tomato

• i didnt make it :/

• koogs i know is not true but i didnt figure out how can i use the sorted array where can use draw function is loop i know but i didnt find another way

• Just implemented @quark's Wikipedia's Bubble Sort article for Java accepting `int[]`: :bz

```/**
* Bubble Sort Int[] (v1.1.3)
* GoToLoop (2017-Feb-02)
*
* https://forum.Processing.org/two/discussion/20601/bubblesort#Item_11
* https://en.Wikipedia.org/wiki/Bubble_sort#Optimizing_bubble_sort
*/

void setup() {
final int[] values = { 6, -9, 2, 1, 0, 7, -9, 3, 1, -5, MAX_INT };
println(str(values));

intBubbleSort(values);
println(str(values)); // -9 -9 -5 0 1 1 2 3 6 7 2147483647

exit();
}

@SafeVarargs static final int[] intBubbleSort(final int... arr)
throws NullPointerException {
int len = max(0, arr.length - 1);

while (len != 0) {
int i = 0, newLen = 0;

while (++i <= len) {
final int left = arr[i - 1], right = arr[i];

if (left > right) { // ascending order
arr[newLen = i - 1] = right;
arr[i] = left;
}
}

len = newLen;
}

return arr;
}
```
• Using "Bubble Sort Int[]" as template, finished adapting it to deal w/ class Bubble now. \m/

However, it didn't work at 1st. Even after sorting the array by diameter! @-)

It failed b/c the Bubble objects aren't display() by their index within their array, but rather their x & y coordinate fields! #-o

So it doesn't matter whether their array is sorted by their diameters or not, they still display() at the same unsorted coordinates! =))

Therefore we've gotta swap their x fields along w/ the diameter-based sorting algorithm! ;))

Well, full solution for "Java Mode" is below. Only thing left is converting it to "p5.js" too: #:-S

```/**
* Bubble[] Sort (v1.2.4)
* GoToLoop (2017-Feb-03)
*
* https://forum.Processing.org/two/discussion/20601/bubblesort#Item_12
* https://en.Wikipedia.org/wiki/Bubble_sort#Optimizing_bubble_sort
*/

import java.util.Comparator;

static final Comparator<Bubble> BUBBLE_X_BY_DIAM = new Comparator<Bubble>() {
@Override final int
compare(final Bubble a, final Bubble b) {
final int diff = a.d - b.d; // ascending order

if (diff > 0) { // swap fields x
final int tmp = a.x;
a.x = b.x;
b.x = tmp;
}

return diff;
}
};

static final int BUBBLES = 5, MIN_DIAM = 10, MAX_DIAM = 80;
final Bubble[] bubbles = new Bubble[BUBBLES];

void setup() {
size(500, 250);
smooth(4);
noLoop();

fill(#FFFF00);
stroke(#FF0000);
strokeWeight(2.5);
ellipseMode(CENTER);

for (int i = 0; i < BUBBLES; bubbles[i++] = new Bubble());
mousePressed();
}

void draw() {
background(0);
for (final Bubble b : bubbles)  b.display();
}

void mousePressed() {
resetBubbles();
println("\nUnsorted Bubbles:");
println(bubbles);

bubbleSort(BUBBLE_X_BY_DIAM, bubbles);
println("Sorted Bubbles by Coord X Based on Diameters:");
println(bubbles);

redraw();
}

void resetBubbles() {
for (int y = height>>1, i = 0; i < BUBBLES; ++i) {
final int x = i*MAX_DIAM + MAX_DIAM;
final int d = (int) random(MIN_DIAM, MAX_DIAM);
bubbles[i].setAllFields(x, y, d);
}
}

@SafeVarargs static final
<T> T[] bubbleSort(final Comparator<T> cmp, final T... arr)
throws NullPointerException {
int len = max(0, arr.length - 1);

while (len != 0) {
int i = 0, newLen = 0;

while (++i <= len) {
final T left = arr[i - 1], right = arr[i];

if (cmp.compare(left, right) > 0) {
arr[newLen = i - 1] = right;
arr[i] = left;
}
}

len = newLen;
}

return arr;
}

class Bubble {
int x = MAX_DIAM, y = height>>1, d = MIN_DIAM;

Bubble() {
}

Bubble(int x, int y, int d) {
setAllFields(x, y, d);
}

Bubble setAllFields(int px, int py, int pd) {
x = px;
y = py;
d = pd;
return this;
}

Bubble display() {
ellipse(x, y, d, d);
return this;
}

@Override String
toString() {
return "x: " + x + " y: " + y + " d: " + d;
}
}
```
• Instead of swapping position x, swap the diameters. I only included the function where I made the relevant changes.

Kf

``````function bubbleSort() {
var temp = 0;
for(var i = 0; i < bubbleArray.length; i++) {
for(var j = 0; j < bubbleArray.length - 1; j++ ) {
if (bubbleArray[j].diameter > bubbleArray[j + 1].diameter) {
temp = bubbleArray[j + 1].diameter;
bubbleArray[j + 1].diameter = bubbleArray[j].diameter;
bubbleArray[j].diameter = temp;
}
}
}
return bubbleArray;
}
``````
• @kfrajer, indeed swapping diameter instead of coordinate x is a viable approach too. *-:)
Regardless, my own Java to p5.js conversion is done. Check it out online too: :-bd
http://CodePen.io/GoSubRoutine/pen/JEvEvb/right/?editors=1011

```/**
* Bubble[] Sort (v1.2.4)
* GoToLoop (2017-Feb-03)
*
* https://forum.Processing.org/two/discussion/20601/bubblesort#Item_14
* https://en.Wikipedia.org/wiki/Bubble_sort#Optimizing_bubble_sort
*
* http://CodePen.io/GoSubRoutine/pen/JEvEvb/right/?editors=1011
*/

"use strict";

const BUBBLES = 5, MIN_DIAM = 10, MAX_DIAM = 80, bubbles = Array(BUBBLES);

function setup() {
createCanvas(500, 250).mousePressed(spawnAndSort);

fill('yellow').stroke('red').strokeWeight(2.5);
ellipseMode(CENTER).noLoop();

for (let i = 0; i < BUBBLES; bubbles[i++] = new Bubble);
spawnAndSort();
}

function draw() {
background(0);
for (let b of bubbles)  b.display();
}

function spawnAndSort() {
resetBubbles();
print('Unsorted Bubbles:');
console.table(bubbles);

bubbleSort();
print('Sorted Bubbles by Coord X Based on Diameters:');
console.table(bubbles);

redraw();
}

function resetBubbles() {
for (let y = height>>1, i = 0; i < BUBBLES; ++i) {
const x = i*MAX_DIAM + MAX_DIAM, d = ~~random(MIN_DIAM, MAX_DIAM);
bubbles[i].setAllFields(x, y, d);
}
}

function bubbleCompare(a, b) {
const diff = a.d - b.d; // ascending order

if (diff > 0) { // swap fields x
const tmp = a.x;
a.x = b.x, b.x = tmp;
}

return diff;
}

function bubbleSort(cmp=bubbleCompare, arr=bubbles) {
let len = max(0, arr.length - 1);

while (len) {
let i = 0, newLen = 0;

while (++i <= len) {
const left = arr[i - 1], right = arr[i];

if (cmp(left, right) > 0) {
arr[newLen = i - 1] = right;
arr[i] = left;
}
}

len = newLen;
}

return arr;
}

class Bubble {
constructor(x=MAX_DIAM, y=height>>1, d=MIN_DIAM) {
this.setAllFields(x, y, d);
}

setAllFields(x, y, d) {
this.x = x, this.y = y, this.d = d;
return this;
}

display() {
ellipse(this.x, this.y, this.d, this.d);
return this;
}

toString() {
return `x: \${this.x} y: \${this.y} d: \${this.d}`;
}
}
```