javascript/school/bubble_sort.js · 1159 字节 · 下载原文
// 冒泡排序 —— 经典排序练习(就地排序一个整数数组)
// Bubble sort -- the classic sorting exercise (sorts an integer array in place)
//
// 来源 / Source: 经典教学实现(Microsoft Learn "Classic Computer Science in JavaScript" / Nicholas C. Zakas)
// https://learn.microsoft.com/archive/blogs/scriptjunkie/classic-computer-science-in-javascript
// 改编 / Adapted: 输出由 return/console 改为本平台的 println_int。
// Output changed to this platform's println_int.
function swap(items, firstIndex, secondIndex) {
var temp = items[firstIndex];
items[firstIndex] = items[secondIndex];
items[secondIndex] = temp;
}
function bubbleSort(items) {
var len = items.length;
var i = 0;
while (i < len) {
var j = 0;
var stop = len - i;
while (j < stop) {
if (items[j] > items[j + 1]) {
swap(items, j, j + 1);
}
j = j + 1;
}
i = i + 1;
}
return items;
}
var data = [5, 3, 9, 1, 7, 3, 0, 8];
var sorted = bubbleSort(data);
for (var k = 0; k < sorted.length; k++) {
println_int(sorted[k]);
}