Skip to content

Commit

Permalink
debug bubble sort
Browse files Browse the repository at this point in the history
  • Loading branch information
iezer committed Aug 21, 2019
1 parent 0176596 commit 4cc652d
Show file tree
Hide file tree
Showing 4 changed files with 113 additions and 0 deletions.
97 changes: 97 additions & 0 deletions ember/algos/app/components/bubble-sort.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
import Component from '@ember/component';
import { schedule } from '@ember/runloop';

export default Component.extend({
step: false,

createLines() {
let { a } = this;
let container = document.querySelector('.bubble-sort');
for (let i = 0; i < a.length; i++) {
let line = document.createElement('div');
line.classList = ['line'];
line.id = `line-${i}`;
line.style.width = `${a[i] * 10}%`;
container.appendChild(line);
}
schedule('afterRender', this, 'bubbleSort');
},

bubbleSort: async function() {
let { a: lines } = this;

for (let i = 0; i < lines.length; i++) {
for (let j = i; j < lines.length; j++) {
if (lines[i] > lines[j]) {
let temp = lines[j];
lines[j] = lines[i];
lines[i] = temp;
this.updateLines(lines);

await new Promise(resolve => {
let checkStep = () => {
setTimeout(() => {
if (this.step) {
resolve();
} else {
checkStep();
}
}, 400);
};

checkStep();
});
}
}
}
},

syncBubbleSort() { // without async/await
let { a: lines } = this;
let promise = Promise.resolve();
for (let i = 0; i < lines.length; i++) {
for (let j = i; j < lines.length; j++) {

let doSwap = (lines, i, j) => {
promise = promise.then(() => {
return new Promise(resolve => {
setTimeout(() => {
if (lines[i] > lines[j]) {
let temp = lines[j];
lines[j] = lines[i];
lines[i] = temp;
this.updateLines(lines);
}
resolve();
}, 100);
});
});
};

doSwap(lines, i, j);
}
}
},

updateLines() {
let { a } = this;
a.forEach((value, index) => {
let line = document.querySelector(`#line-${index}`);
line.style.width = `${value * 10}%`;
});
},

didInsertElement() {
this._super(...arguments);

this.a = [10, 9, 8, 7, 6, 5, 4, 3, 2, 1];

schedule('afterRender', this, 'createLines');
},

actions: {
step() {
this.toggleProperty('step');
}
}
});
10 changes: 10 additions & 0 deletions ember/algos/app/styles/app.scss
Original file line number Diff line number Diff line change
Expand Up @@ -85,3 +85,13 @@
border: 1px solid;
}
}

.bubble-sort {
width: 400px;

.line {
background-color: red;
height: 10px;
margin-bottom: 10px;
}
}
2 changes: 2 additions & 0 deletions ember/algos/app/templates/application.hbs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
<BubbleSort />

<MinHeap />

<TicTacToe />
Expand Down
4 changes: 4 additions & 0 deletions ember/algos/app/templates/components/bubble-sort.hbs
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
<div class="bubble-sort">
</div>

<button {{action "step"}}>{{if this.step "Pause" "Start"}}</button>

0 comments on commit 4cc652d

Please sign in to comment.