Home >Web Front-end >JS Tutorial >JavaScript algorithm learning (direct insertion sorting)_javascript skills

JavaScript algorithm learning (direct insertion sorting)_javascript skills

WBOY
WBOYOriginal
2016-05-16 18:07:561179browse

1. Basic idea
Assume that the records to be sorted are stored in the array R[1..n]. Initially, R[1] forms an ordered area, and the unordered area is R[2..n]. From i=2 until i=n, ​​R[i] is inserted into the current ordered area R[1..i-1] in sequence, generating an ordered area containing n records.

Copy code The code is as follows:


javascript direct insertion sorting


< body>
<script> <br>var arr = []; <br>for(var i=0;i<20; i) <BR>{ <BR>arr.push(~~(Math. random()*20)); <BR>} <BR>document.write(arr "<br/>"); <br>Array.prototype.insertionSort = function() <br>{ <br>var j; <br>var value; <br>for(var i=1;i<this.length;i ) <BR>{ <BR>j=i; <BR>value = this[j]; <BR> while(j>0 && this[j-1]>value) <br>{ <br>this[j] = this[j-1]; <br>j--; <br>} <br>this [j] = value; <br>} <br>} <br>arr.insertionSort(); <br>document.write(arr "<br/>"); <br></script>


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn