首页 > 代码库 > 冒泡与快排

冒泡与快排

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>

<body>
<script>
// var arr = [6,10,2,9,3,8,11,4,5];

var arr = [];
for (var i=0; i<100000; i++) {
arr.push(i);
}
arr.sort(function () {
return Math.random() - 0.5;
});

// console.time(‘a‘);
// bubbleSort(arr);
// console.timeEnd(‘a‘);

console.time(‘a‘);
quickSort(arr);
console.timeEnd(‘a‘);

console.log(arr);

// console.log(arr);

function bubbleSort() {
for ( var j=0; j<arr.length-1; j++ ) {
var flag = true;

for (var i=0; i<arr.length-1-j; i++) {
var a = arr[i];
var b = arr[i+1];
if (a > b) {
flag = false;
arr[i] = b;
arr[i+1] = a;
}
}
if (flag) {
break;
}
}
}

function quickSort(data, start, end) {

// 确定要处理的数据的起始位置和结束位置
var start = start || 0;
if (end === undefined) {
end = data.length - 1;
}

if (start >= end) {
return;
}

var v = data[start];

var i = start;
var j = end;

while (i < j) {

while (data[j] > v && i < j) {
j--;
}
data[i] = data[j];

while (data[i] < v && i < j) {
i++;
}
data[j] = data[i];

}

data[i] = v;

quickSort(data, start, i - 1);
quickSort(data, i + 1, end );

}
</script>
</body>
</html>

冒泡与快排