let arr=[5,7,5,8,1,2,9,10,51]; let len=arr.length; function a(arr){ if(arr==null||arr.length<2) {return null;} for(let i=0;i<len;i++){ heapinsert(arr,i); } let size=arr.length; swap(arr,0,--size); while(size>0){ heap(arr,0,size); swap(arr,0,--size); } return arr; } function heapinsert(arr,i){ while(arr[i]>arr[Math.floor((i-1)/2)]){ swap(arr,i,Math.floor((i-1)/2)); i=Math.floor((i-1)/2); } } function heap(arr,index,size){ let left=index*2 + 1; while(left<size){ let lag=left+1<size && arr[left]<arr[left+1]?left+1:left; lag=arr[index]<arr[lag]?lag:index; if(lag===index){ break; } swap(arr,lag,index) index=lag; left=index*2+1; } } function swap(arr,i,j){ let tmp=arr[i]; arr[i]=arr[j]; arr[j]=tmp; } let b=a(arr); console.log(b);