function bubbleSort( arr ) {
for( var i = 0;i < arr.length - 1;i++ ){
var judge = false;
for( var j = 0;j < arr.length - 1 - i;j++ ){
if( arr[j] > arr[j+1] ){
var tmp = arr[j+1];
arr[j+1] = arr[j];
arr[j] = tmp;
judge = true;
}
}
console.log( panduan );
if( !judge ){
break;
}
}
return arr;
}
//选择排序
function selectSort( arr ) {
for( var i = 0;i < arr.length - 1;i++ ){
var maxIndex = i;
for( var j = i+1;j < arr.length;j++ ){
if( arr[j] > arr[maxIndex] ){
maxIndex = j;
}
}
var tmp = arr[maxIndex];
arr[maxIndex] = arr[i];
arr[i] = tmp;
}
return arr;
}
//插入排序
function insertSort( arr ) {
for( var i = 1;i < arr.length;i++ ) {
var curValue = arr[i];
var preIndex = i - 1;
while( preIndex >= 0 && arr[preIndex] < curValue ){
arr[preIndex + 1] = arr[preIndex];
preIndex --;
}
arr[preIndex+1] = curValue;
}
return arr;
}
//快速排序
function quickSort( arr ) {
if( arr.length <= 1 ){
return arr;
}
var pivotIndex = Math.floor( arr.length / 2 );
var prvot = arr.splice( pivotIndex,1 )[0];
var left = [];
var right = [];
for(var i = 0;i < arr.length;i++ ){
if( arr[i] < prvot ){
left.push( arr[i] );
}else{
right.push( arr[i] );
}
}
return quickSort( left ).concat( [prvot], quickSort( right ) );
}
js实现的冒泡排序、选择排序、插入排序、快速排序
最新推荐文章于 2022-08-18 13:53:23 发布