代码部分
var arr = [6,9,5,3,7,2,8]
//比较值的大小
var less = function (x, y) {
return x < y
}
//调换位置
var exch = function (arr, x , y) {
var t = arr[x]
arr[x] = arr[y]
arr[y] = t
}
//寻找切分点
var partition = function (arr, si, ei){
var i = si, j = ei + 1
var v = arr[si] //切分元素
while (true){
while (less(arr[++i], v)) if(i == ei) break;
while (less(v, arr[--j])) if(j == si) break;
if(i >= j) break;
exch(arr, i, j)
}
exch(arr, si , j)
return j
}
var sort = function (arr, si, ei) {
if(ei <= si) return;
var pt = partition(arr, si, ei)
sort(arr,si, pt - 1)
sort(arr, pt + 1, ei)
}
sort(arr, 0, arr.length - 1)
console.log(arr)
快速排序
var arr = [9,2,3,8,5,7]
function quickSort(arr){
if (arr.length <= 1) { return arr; }
var index = Math.floor(arr.length/2)
var mid = arr.splice(index, 1)[0]
var left = []
var right = []
for(var i=0; i < arr.length; i++){
if(arr[i] <= mid){
left.push(arr[i])
}else{
right.push(arr[i])
}
}
return quickSort(left).concat([mid], quickSort(right))
}
console.log(quickSort(arr))
冒泡排序
//选择排序
var arr = [2,7,0,4,6,3,8]
function less(x, y){
return x < y
}
function each(arr, j ,i){
var a = arr[j]
arr[j] = arr[i]
arr[i] = a
}
function sort(arr){
var len = arr.length
for(var i = 0;i < len; i++){
var min = i
for(var j = i + 1; j < len; j++){
if(less(arr[j],arr[min])){
min = j
}
}
each(arr, i, min)
}
return arr
}
console.log(sort(arr))