1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
| var S; var Coordinate_y = 40; var Rect = new Array(); var track_insert = new Array(); var cons = 0; var cnt;
function func() {
S = document.getElementsByName("string")[0].value.split("");
for (var i = 0; i < S.length; i++) { var rect = { x: 30 * i, y: Coordinate_y, target_x: 30 * i, target_y: Coordinate_y, text: S[i] } Rect.push(rect); } insertSort(S); }
function insertSort(arr) { var i = 1, j, key, temp; for (; i < arr.length; i++) { j = i; key = arr[i]; while (--j >= 0) { if (arr[j] > key) { arr[j + 1] = arr[j]; arr[j] = key;
track_insert.push(j); } else { break; } } } }
function update() { if (cons > track_insert.length) { return; } if (cons == 0) { cnt = track_insert[cons]; Rect[cnt].target_x = Rect[cnt + 1].x; Rect[cnt + 1].target_x = Rect[cnt].x; cons += 1; console.log(cnt); } if (Rect[cnt].x == Rect[cnt].target_x) { if (cons == track_insert.length) { cons += 1; return; } var tem = Rect[cnt]; Rect[cnt] = Rect[cnt + 1]; Rect[cnt + 1] = tem; cnt = track_insert[cons]; Rect[cnt].target_x = Rect[cnt + 1].x; Rect[cnt + 1].target_x = Rect[cnt].x; cons += 1; console.log(cnt); } else { Rect[cnt].x += 1; Rect[cnt + 1].x -= 1; } }
function draw(context) { context.clearRect(0, 0, context.canvas.width, context.canvas.height); for (var i = 0; i < Rect.length; i++) { if ((Rect[i].x - Rect[i].target_x) >= 2 || (Rect[i].x - Rect[i].target_x) < -2) { context.fillStyle = "yellow"; context.fillRect(Rect[i].x, Rect[i].y, 25, 25); context.fillStyle = "blue"; context.fillText(Rect[i].text, Rect[i].x + 10, Rect[i].y + 15); } else { context.strokeStyle = "blue"; context.strokeRect(Rect[i].x, Rect[i].y, 25, 25); context.fillStyle = "blue"; context.fillText(Rect[i].text, Rect[i].x + 10, Rect[i].y + 15); } } context.fillText("插入排序", 40, 80); } function showDemo() { func(); var c = document.getElementById("mycanvas"); c.width = 600; c.height = 300; var context = c.getContext("2d");
setInterval(function() { draw(context); update(); }, 40); }
|