本文实现的排序算法有:冒泡排序、选择排序、插入排序、希尔排序、快速排序。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
| function ArrayList() { this.array = [] ArrayList.prototype.insert = function (item) { this.array.push(item) } ArrayList.prototype.toString = function () { return this.array.join(' ') } ArrayList.prototype.bubbleSort = function () { var length = this.array.length for (let j = length - 1; j >= 0; j--) { for (let i = 0; i < j; i++) { if (this.array[i] > this.array[i + 1]) { this.swap(i, i + 1) } } } } ArrayList.prototype.selectionSort = function () { var length = this.array.length for (let j = 0; j < length - 1; j++) { var min = j for (let i = min + 1; i < length; i++) { if (this.array[i] < this.array[min]) { min = i } } this.swap(j, min) } } ArrayList.prototype.insertionSort = function () { var length = this.array.length for (let i = 1; i < length; i++) { var cur = this.array[i] var j = i while (cur < this.array[j - 1] && j > 0) { this.array[j] = this.array[j - 1] j-- } this.array[j] = cur } } ArrayList.prototype.shellSort = function () { var length = this.array.length var gap = length / 2 | 0 while (gap >= 1) { for (let i = gap; i < length; i++) { var cur = this.array[i] var j = i while (cur < this.array[j - gap] && j > gap - 1) { this.array[j] = this.array[j - gap] j -= gap } this.array[j] = cur } gap = gap / 2 | 0 } } ArrayList.prototype.quickSort = function () { this.quick(0, this.array.length - 1) } ArrayList.prototype.quick = function (left, right) { if (left >= right) return var pivot = this.median(left, right) var i = left var j = right - 1 while (i < j) { while (this.array[++i] < pivot) { } while (this.array[--j] > pivot) { } if (i >= j) { break } else { this.swap(i, j) } } this.swap(i, right - 1) this.quick(left, i - 1) this.quick(i + 1, right) } ArrayList.prototype.swap = function (m, n) { [this.array[m], this.array[n]] = [this.array[n], this.array[m]] } ArrayList.prototype.median = function (left, right) { var center = (left + right) / 2 | 0 if (this.array[left] > this.array[center]) { this.swap(left, center) } if (this.array[left] > this.array[right]) { this.swap(left, right) } if (this.array[center] > this.array[right]) { this.swap(center, right) } this.swap(center, right - 1) return this.array[right - 1] } }
var list = new ArrayList() list.insert(97) list.insert(35) list.insert(12) list.insert(9) list.insert(20) list.insert(66) list.insert(77) list.insert(45) list.insert(2) list.insert(6) list.quickSort() alert(list.toString())
|