Skip to content

Instantly share code, notes, and snippets.

@korrio
Created July 10, 2019 06:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save korrio/6136f79e71b1f52d695124e30bcd81b8 to your computer and use it in GitHub Desktop.
Save korrio/6136f79e71b1f52d695124e30bcd81b8 to your computer and use it in GitHub Desktop.
sort
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div id="app">
<table border="1">
<tr v-for="(item, index) of items" :key="index">
<td><input type="radio" :checked="i == index" v-on:click="i = index" /></td>
<td><input type="radio" :checked="j == index" v-on:click="j = index" /></td>
<td>{{item}}</td>
<td>
<div :style="{width:item*40+'px'}" style="background:black">&nbsp;</div>
</td>
</tr>
</table>
<p>
<button v-on:click="shuffle">shuffle</button>
<button v-on:click="swap(j,j-1)">swap</button>
<button v-on:click="sort">sort</button>
</p>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.10/dist/vue.js"></script>
<script>
new Vue({
el: '#app',
data: {
i: 0,
j: 1,
items: [12, 7, 8, 5, 13, 2, 15, 9, 11, 6, 3, 10, 4, 14, 1]
},
methods: {
shuffle: function () {
this.items = s(this.items)
console.log(this.items)
},
swap: function (a, b) {
const temp = this.items[a]
this.items[a] = this.items[b]
this.items[b] = temp
this.items = this.items.slice()
// ;[this.items[this.i], this.items[this.j]] = [
// this.items[this.i],
// this.items[this.j]
// ]
// console.log("i:" + this.i + " j:" + this.j)
// console.log(this.items)
},
sort: function () {
for (var i = 1; i < this.items.length; i++) {
var j = i
for (; j > 0 && this.items[j] < this.items[j - 1]; j = j - 1) {
console.log("i:" + i + " j:" + j)
var vm = this;
vm.swap(j, j - 1)
}
}
}
}
})
function s(a) {
var j, x, i;
for (i = a.length - 1; i > 0; i--) {
j = Math.floor(Math.random() * (i + 1));
x = a[i];
a[i] = a[j];
a[j] = x;
}
return a;
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment