常用的javascript数组排序

1、冒泡排序


<script type="text/javascript">
var newArr = [2, 1, 3, 5, 4];

function bubbleSort(arr) {
for (var i = 0; i < arr.length; i++) {
for (var j = 0; j < arr.length - 1 - i; j++) {
if (arr[j] > arr[j + 1]) { //相邻元素两两对比
var temp = arr[j + 1]; //元素交换
arr[j + 1] = arr[j];
arr[j] = temp;
}
}
}
return arr;
}

console.log(bubbleSort(newArr)); //[1, 2, 3, 4, 5]
</script>


2、插入排序


<script type="text/javascript">
var newArr = [2, 1, 3, 5, 4];

function insertionSort(arr) {
var len = arr.length;
var preIndex, current;
for (var i = 1; i < len; i++) {
preIndex = i - 1;
current = arr[i];
while (preIndex >= 0 && arr[preIndex] > current) {
arr[preIndex + 1] = arr[preIndex];
preIndex--;
}
arr[preIndex + 1] = current;
}
return arr;
}

console.log(insertionSort(newArr)); //[1, 2, 3, 4, 5]
</script>


3、快速排序


<script type="text/javascript">
var newArr = [2, 1, 3, 5, 4];

function quickSort(arr, left, right) {
var len = arr.length,
partitionIndex,
left = typeof left != 'number' ? 0 : left,
right = typeof right != 'number' ? len - 1 : right;

if (left < right) {
partitionIndex = partition(arr, left, right);
quickSort(arr, left, partitionIndex - 1);
quickSort(arr, partitionIndex + 1, right);
}
return arr;
}

function partition(arr, left, right) { //分区操作
var pivot = left, //设定基准值(pivot)
index = pivot + 1;
for (var i = index; i <= right; i++) {
if (arr[i] < arr[pivot]) {
swap(arr, i, index);
index++;
}
}
swap(arr, pivot, index - 1);
return index - 1;
}

function swap(arr, i, j) {
var temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}

console.log(quickSort(newArr)); //[1, 2, 3, 4, 5]
</script>


 

转载请注明来源:开发猿 » 常用的javascript数组排序

赞 (1) 打赏

觉得文章有用就打赏一下哦

支付宝扫一扫打赏

微信扫一扫打赏