var arr = [8, 34, 67, 45, 5, 68, 2, 40, 4, 13, 60];
arr = [5, 1, 1, 2, 0, 0];
arr = quickSort(arr);
function quickSort(arr) {
if (arr.length <= 1) {
return arr;
}
var length = arr.length;
var basic = arr[length - 1]; // 这里为理解方便取数组最后一个数据作为基数
var leftPoint = 0; // 左指针取第一个数据
var rightPoint = length - 2; // 右指针取倒二个数据
var temp;
//左指针向右移动直到数据比基数大
while (leftPoint != rightPoint) {
while (arr[leftPoint] <= basic && leftPoint < rightPoint) {
leftPoint++;
}
// 右指针向左移动直到比基数小
while (arr[rightPoint] > basic && rightPoint > leftPoint) {
rightPoint--
}
// 交换左右指针的值
if (leftPoint != rightPoint) {
temp = arr[leftPoint];
arr[leftPoint] = arr[rightPoint];
arr[rightPoint] = temp;
}
// 交换完成后 指针继续向右移动
}
var hasChangeBasic = false;
// 当指针交汇的时候,将基数同该指针数据交换
if (rightPoint != length - 1 && arr[rightPoint] > basic) {
// 若右指针没有移动,说明基数已经是最大的了,不用进行交换
arr[length - 1] = arr[rightPoint];
arr[rightPoint] = basic;
hasChangeBasic = true;
}
var arrLeft = [];
var arrRight = [];
if (hasChangeBasic === false) {
//基数没有被交换,则数组左边全部比基数小
arrLeft = arr.slice(0, length - 1);
} else {
arrLeft = arr.slice(0, leftPoint);
arrRight = arr.slice(rightPoint + 1, length);
}
var arrLeft = quickSort(arrLeft);
var arrRight = quickSort(arrRight);
arr = arrLeft.concat([basic]).concat(arrRight)
return arr;
}
算法学习小记-1.排序算法-1.1快速排序
最新推荐文章于 2020-10-21 23:08:38 发布