JS中的排序
直接使用给定规则的sort() 七行手撕快排 正常手撕快排
直接使用给定规则的sort()
function MySort ( arr ) {
return arr. sort ( ( a, b ) => {
return a- b
} )
}
module. exports = {
MySort : MySort
} ;
七行手撕快排
function MySort ( arr ) {
if ( arr. length<= 1 ) return arr;
const current= arr. splice ( arr. length/ 2 , 1 ) [ 0 ]
let left= [ ] , right= [ ]
arr. forEach ( ele => {
( ele> current? right: left) . push ( ele)
} )
return MySort ( left) . concat ( current, MySort ( right) )
}
module. exports = {
MySort : MySort
} ;
正常手撕快排
function MySort ( arr ) {
return quick ( arr, 0 , arr. length- 1 )
}
function quick ( arr, left, right ) {
let index
if ( arr. length> 1 ) {
index= partition ( arr, left, right)
if ( left< index- 1 ) {
quick ( arr, left, index- 1 )
}
if ( index< right) {
quick ( arr, index, right)
}
}
return arr
}
function partition ( arr, left, right ) {
const pivot= arr[ left]
let i= left, j= right
while ( i<= j) {
while ( arr[ i] < pivot) {
i++
}
while ( arr[ j] > pivot) {
j--
}
if ( i<= j) {
[ arr[ i] , arr[ j] ] = [ arr[ j] , arr[ i] ]
i++
j--
}
}
return i
}
module. exports = {
MySort : MySort
} ;