function ArrayList() {
// 定义属性
this.arrys = []
// 内部方法
// 调换位置
ArrayList.prototype.swap = function (m, n) {
let temp = this.arrys[m]
this.arrys[m] = this.arrys[n]
this.arrys[n] = temp
}
// 快速排序--选择枢纽
ArrayList.prototype.median = function (left, right) {
let center = Math.floor((left + right) / 2)
if (this.arrys[left] > this.arrys[center]) {
this.swap(left, center)
}
if (this.arrys[left] > this.arrys[right]) {
this.swap(left, right)
}
if (this.arrys[center] > this.arrys[right]) {
this.swap(center, right)
}
this.swap(center, right - 1)
return this.arrys[right - 1]
}
// 方法
// 添加属性
ArrayList.prototype.insert = function (item) {
return this.arrys.push(item)
}
// 转化为字符串
ArrayList.prototype.toString = function () {
return this.arrys.join(' ')
}
// 冒泡排序
ArrayList.prototype.bubbleSort = function () {
let length = this.arrys.length;
for (let i = 0; i < length - 1; i++) {
for (let j = 0; j < length - i - 1; j++) {
if (this.arrys[j] > this.arrys[j + 1]) {
this.swap(j, j + 1)
}
}
}
}
// 选择排序
ArrayList.prototype.selectionSort = function () {
let length = this.arrys.length;
for (let i = 0; i < length - 1; i++) {
let min = i
for (let j = min + 1; j < length; j++) {
if (this.arrys[min] > this.arrys[j]) {
min = j
}
}
this.swap(min, i)
}
}
//插入排序
ArrayList.prototype.insertionSort = function () {
let length = this.arrys.length
for (let i = 1; i < length; i++) {
let temp = this.arrys[i]
let j = i
while (this.arrys[j - 1] > temp && j > 0) {
this.arrys[j] = this.arrys[j - 1]
j--
}
this.arrys[j] = temp
}
}
// 希尔排序 -- 原稿增量
ArrayList.prototype.shellSort = function () {
let length = this.arrys.length
// 初始化增量
let gap = Math.floor(length / 2)
while (gap >= 1) {
for (let i = gap; i < length; i++) {
let temp = this.arrys[i]
let j = i
while (this.arrys[j - gap] > temp && j >= gap - 1) {
this.arrys[j] = this.arrys[j - gap]
j -= gap
}
this.arrys[j] = temp
}
// 改变增量
gap = Math.floor(gap / 2)
}
}
// 快速排序
ArrayList.prototype.quickSort = function () {
this.quick(0, this.arrys.length - 1)
}
ArrayList.prototype.quick = function (left, right) {
// 结束条件
if (left >= right) return;
// 获取中枢
let pivot = this.median(left, right)
// 定义变量 记录找到的值
let i = left
let j = right - 1
while (i < j) {
while (this.arrys[++i] < pivot) { }
while (this.arrys[--j] > pivot) { }
if (i < j) {
this.swap(i, j)
} else {
break
}
}
// 将枢纽放在正确的位置
this.swap(i, right - 1)
// 递归调用
this.quick(left, i - 1)
this.quick(i + 1, right)
}
}