<script type="text/javascript">
//从小到大
var arr = [12, 3, 56, 45, 25, 8, 6, 5, 40];
//冒泡排序(时间复杂度n2,空间复杂度1,稳定)
var temp;
for(var i = 0; i < arr.length ; i++) {
for(var j = 0; j < arr.length; j++) {
if(arr[j] > arr[j + 1]) {
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
for(var i = 0; i < arr.length; i++) {
console.log(arr[i])
}
</script>
<script type="text/javascript">
//从小到大
var arr = [12, 3, 56, 45, 25];
//选择排序(时间复杂度n2,空间复杂度1,不稳定)
var temp;
var min;
for(var i = 0; i < arr.length; i++) {
min = i;
for(var j = i + 1; j < arr.length; j++) {
if(arr[min] > arr[j]) {
min = j;
}
}
temp = arr[min];
arr[min] = arr[i];
arr[i] = temp;
}
for(var i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
</script>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript">
var arr = [12, 3, 56, 45, 25, 5, 36, 95, 62];
quickSort(arr);
for(var i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
function quickSort(array) {
function sort(low, high) {
var i = low;
var j = high - 1;
var flag = array[low];
if((high - low) > 1) {
while(i < j) {
for(; i < j; j--) {
if(array[j] < flag) {
array[i++] = array[j]; //a[i] = a[j]; i += 1;
break;
};
}
for(; i < j; i++) {
if(array[i] > flag) {
array[j--] = array[i];
break;
}
}
}
array[i] = flag;
sort(0, i - 1);
sort(i + 1, high);
}
}
sort(0, array.length);
return array;
}
</script>
</head>
<body>
</body>
</html>