function qSort(arr) { if (arr.length <=1) { return arr; } var left = []; var right = []; var pivot = arr[0]; for ( var i = 1; i < arr.length; i++) { if (arr[i] < pivot) { left.push(arr[i]); } else { right.push(arr[i]); } } return qSort(left).concat(pivot, qSort(right)); } var a = new Array(23); function setData(a) { for ( var i = 0; i < a.length; ++i) { a[i] = Math.floor((Math.random() * 100) + 1); } } function prints(arr) { for ( var i = 0; i < arr.length; ++i) { document.write(arr[i] + " "); if (i > 0 & i % 10 == 0) { document.write("<br />"); } } } setData(a); var b = qSort(a);//注意qSort()方法是有返回值的,而不是直接对a进行操作 prints(b);
时间: 2024-10-08 02:59:27