js简单排序
1.先封装一个列表
function ArrayList(){
this.array=[]
ArrayList.prototype.insert=function(item){
this.array.push(item)
}
ArrayList.prototype.toString=function(){
return this.array.join('-')
}
}
- 冒泡排序
ArrayList.prototype.bubbleSort=function(){
for(var j=1;j<this.array.length;j++){
for (var i=0;i<this.array.length-j;i++) {
var next=this.array[i+1]
if(this.array[i]>this.array[i+1]){
this.array[i+1]=this.array[i]
this.array[i]=next
}
}
}
}
- 选择排序
ArrayList.prototype.selectionSort=function(){
var length=this.array.length
for (var j=0;j<length;j++) {
var min=j
for (var i=j;i<length-1;i++) {
if(this.array[min]>this.array[i+1]){
min=i+1
}
}
var minValue=this.array[min]
this.array[min]=this.array[j]
this.array[j]=minValue
}
}
- 插入排序
ArrayList.prototype.insertSort=function(){
var length=this.array.length
var mark=0
var place=0
for (var i=0;i<length-1;i++) {
mark=i+1
for (var j=mark-1;j>=0;j--) {
if(this.array[j]>this.array[j+1]){
place=this.array[j+1]
this.array[j+1]=this.array[j]
this.array[j]=place
}else{
break
}
}
}
}