排序
冒泡排序
Array.prototype.bobuleSort=function(){
for(let j=0;j<this.length-1;j++){
for(let i=0;i<this.length-1-j;i++){
if(this[i]>this[i+1]){
let temp=this[i];
this[i]=this[i+1];
this[i+1]=temp;
}
}
}
}
const arr=[5,4,3,2,1];
arr.bobuleSort();
console.log(arr);
选择排序
Array.prototype.selectionSort=function(){
for(let i=0;i<this.length-1;i++){
let minIndex=i;
for(let j=i;j<this.length;j++){
if(this[j]<this[minIndex]){
minIndex=j;
}
}
if(minIndex!=i){
let temp=this[i];
this[i]=this[minIndex];
this[minIndex]=temp;}
}
}
const arr=[1,2,3,4,5];
arr.selectionSort();
console.log(arr);
插入排序
Array.prototype.insertSort=function(){
for(let i=0;i<this.length;i++){
let temp=this[i];
let j=i;
while(j>0){
if(this[j-1]>temp){
this[j]=this[j-1];
}else{break}
j--;
}
this[j]=temp;
}
}
const arr=[5,4,3,2,1,6,9,8,7];
arr.insertSort();
console.log(arr);
归并排序
Array.prototype.mergeSort=function(){
const rec=(arr)=>{
if(arr.length==1){return arr}
let mid=Math.floor(arr.length/2);
let left=arr.slice(0,mid);
let right=arr.slice(mid,arr.length);
let orderLeft=rec(left);
let orderRight=rec(right);
let res=[];
while(orderLeft.length||orderRight.length){
if(orderLeft.length&&orderRight.length){
res.push(orderLeft[0]<orderRight[0]?orderLeft.shift():orderRight.shift())
}else if(orderLeft.length){
res.push(orderLeft.shift());
}else if(orderRight.length){
res.push(orderRight.shift())
}
}
return res;
}
const res=rec(this);
res.forEach((n,i) =>{this[i]=n} );
}
const arr=[5,4,3,2,1];
arr.mergeSort();
console.log(arr);
快速排序
Array.prototype.quickSort=function(){
const rec=(arr)=>{
if(arr.length===1){return arr}
let left=[];
let right=[];
let mid=arr[0];
for(let i=1;i<arr.length;i++){
if(arr[i]<mid){
left.push(arr[i]);
}else{right.push(arr[i]);
}
}
return [...rec(left),mid,...rec(right)]
}
const res=rec(this);
res.forEach((n,i) =>{this[i]=n} );
}
const arr=[5,4,3,2,1];
arr.quickSort();
console.log(arr);
搜索
顺序搜索
Array.prototype.squeentailSearch=function (item){
for(let i=0;i<this.length;i++){
if(this[i]===item){
return i
}
}
return -1
}
let arr=[5,4,3,6,2,1];
let index=arr.squeentailSearch(2);
console.log(index);
二分搜索
Array.prototype.binarySearch=function(item){
let low=0;
let high=this.length-1;
while(low<=high){
let mid=Math.floor((low+high)/2);
let element=this[mid];
if(item<element){high=mid-1;}
else if(item>element){low=mid+1;}
else{ return mid}
}
return -1
}
const arr=[2,4,5,6,1,3,7];
let index=arr.binarySearch(5);
console.log(index);
合并两个有序链表
var mergeTwoLists = function(list1, list2) {
let res=new ListNode(0);
let p=res;
let p1=list1;
let p2=list2;
while(p1&&p2){
if(p1.val<p2.val){
p.next=p1;
p1=p1.next;}
else{
p.next=p2;
p2=p2.next;
}
p=p.next
}
if(p1){
p.next=p1;
}
if(p2){
p.next=p2;
}
return res.next
};
猜数游戏
var guessNumber = function(n) {
let low=0;
let high=n;
while(low<=high){
let mid=Math.floor((low+high)/2);
let res=guess(mid);
if(res===-1){
high=mid-1;
}
else if(res===0){
return mid
}else{
low=mid+1
}
}
};