Javascript中的常见排序算法

2019-06-03 00:49:21王振洲

 { 
 for (var j = i + step; j < this.length; j += step) 
 { 
 var k = j, value = this[j]; 
 while (k >= step && this[k - step] > value) 
 { 
 this[k] = this[k - step]; 
 k -= step; 
 } 
 this[k] = value; 
 } 
 } 
 } 
 } 
 Array.prototype.quickSort = function(s, e) 
 { 
 if (s == null) s = 0; 
 if (e == null) e = this.length - 1; 
 if (s >= e) return; 
 this.swap((s + e) >> 1, e); 
 var index = s - 1; 
 for (var i = s; i <= e; ++i) 
 { 
 if (this[i] <= this[e]) this.swap(i, ++index); 
 } 
 this.quickSort(s, index - 1); 
 this.quickSort(index + 1, e); 
 } 
 Array.prototype.stackQuickSort = function() 
 { 
 var stack = [0, this.length - 1]; 
 while (stack.length > 0) 
 { 
 var e = stack.pop(), s = stack.pop(); 
 if (s >= e) continue; 
 this.swap((s + e) >> 1, e); 
 var index = s - 1; 
 for (var i = s; i <= e; ++i) 
 { 
 if (this[i] <= this[e]) this.swap(i, ++index); 
 } 
 stack.push(s, index - 1, index + 1, e); 
 } 
 } 
 Array.prototype.mergeSort = function(s, e, b) 
 { 
 if (s == null) s = 0; 
 if (e == null) e = this.length - 1; 
 if (b == null) b = new Array(this.length); 
 if (s >= e) return; 
 var m = (s + e) >> 1; 
 this.mergeSort(s, m, b); 
 this.mergeSort(m + 1, e, b); 
 for (var i = s, j = s, k = m + 1; i <= e; ++i) 
 { 
 b[i] = this[(k > e || j <= m && this[j] < this[k]) ? j++ : k++];