Download code

Jump to: navigation, search

Back to Merge_sort_(JavaScript)

Download for Windows: zip

Download for UNIX: zip, tar.gz, tar.bz2

mergesort.js

 1 /* The authors of this work have released all rights to it and placed it
 2 in the public domain under the Creative Commons CC0 1.0 waiver
 3 (http://creativecommons.org/publicdomain/zero/1.0/).
 4 
 5 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 6 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 7 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 8 IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
 9 CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
10 TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
11 SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
12 
13 Retrieved from: http://en.literateprograms.org/Merge_sort_(JavaScript)?oldid=19176
14 */
15 
16 
17 Array.prototype.swap=function(a, b)
18 {
19 	var tmp=this[a];
20 	this[a]=this[b];
21 	this[b]=tmp;
22 }
23 
24 function insert(array, begin, end, v)
25 {
26 	while(begin+1<end && array[begin+1]<v) {
27 		array.swap(begin, begin+1);
28 		++begin;
29 	}
30 	array[begin]=v;
31 }
32 
33 function merge(array, begin, begin_right, end)
34 {
35 	for(;begin<begin_right; ++begin) {
36 		if(array[begin]>array[begin_right]) {
37 			var v=array[begin];
38 			array[begin]=array[begin_right];
39 			insert(array, begin_right, end, v);
40 		}
41 	}
42 }
43 
44 function msort(array, begin, end)
45 {
46 	var size=end-begin;
47 	if(size<2) return;
48 
49 	var begin_right=begin+Math.floor(size/2);
50 
51 	msort(array, begin, begin_right);
52 	msort(array, begin_right, end);
53 	merge(array, begin, begin_right, end);
54 }
55 
56 function merge_sort(array)
57 {
58 	msort(array, 0, array.length);
59 }
60 
61 function dosort(form)
62 {
63 	var array=form.unsorted.value.split(/ +/);
64 
65 	merge_sort(array);
66 
67 	form.sorted.value=array.join(' ');
68 
69 
70 }
71 
72 


hijacker
hijacker
hijacker
hijacker

mergesort.html

 1 <html>
 2 <head>
 3  <title>Merge sort test</title>
 4   <script type="text/javascript" src="mergesort.js" >
 5   </script>
 6 </head>
 7 <body>
 8  <form id="msform" action="" method="" >
 9   <input type="text" size="80" name="unsorted" 
10    value="Paris London Stockholm Berlin Oslo Rome Madrid Tallinn Amsterdam Dublin" /> <br />
11   <input type="button" name="sort" value="Sort" onclick="dosort(this.form)" /> <br />
12   <input type="text" size="80" name="sorted" value="" />
13  </form>
14 </body>
15 </html>


hijacker
hijacker
hijacker
hijacker