冒泡排序
let ary = [ 12 , 24 , 45 , 2 , 6 , 2 , 7 , 0 , 2 , 1 ] ;
function BubbleSort ( ary) {
for ( let i = 0 ; i < ary. length - 1 ; i++ ) {
for ( let j = 0 ; j < ary. length - 1 - i; j++ ) {
let temp = null ;
if ( ary[ j] > ary[ j + 1 ] ) {
[ ary[ j + 1 ] , ary[ j] ] = [ ary[ j] , ary[ j + 1 ] ] ;
}
}
}
return ary
}
console. log ( BubbleSort ( ary) ) ;
插入排序
let ary = [ 12 , 24 , 45 , 2 , 6 , 2 , 7 , 0 , 2 , 1 ] ;
function insertSort ( ary) {
let handle = [ ary[ 0 ] ] ;
for ( let i = 0 ; i < ary. length; i++ ) {
let A = ary[ i] ;
for ( let j = handle. length - 1 ; j >= 0 ; j-- ) {
let B = handle[ j] ;
if ( A > B ) {
handle. splice ( j + 1 , 0 , A ) ;
break ;
}
if ( j === 0 ) {
handle. unshift ( A ) ;
}
}
}
return handle;
}
console. log ( insertSort ( ary) ) ;
快速排序
let ary = [ 12 , 24 , 45 , 2 , 6 , 2 , 7 , 0 , 2 , 1 ] ;
function quickSort ( arr) {
if ( arr. length <= 1 ) {
return arr;
}
let middleIndex = Math. floor ( arr. length / 2 ) ;
let middleValue = arr. splice ( middleIndex, 1 ) [ 0 ] ;
let arrLeft = [ ] ;
let arrRight = [ ] ;
for ( let i = 0 ; i < arr. length; i++ ) {
let item = arr[ i] ;
item > middleValue ? arrRight. push ( item) : arrLeft. push ( item) ;
}
return [ ... quick ( arrLeft) , middleValue, ... quick ( arrRight) ] ;
}
console. log ( quickSort ( ary) ) ;