javascript排序算法
冒泡排序
// 创建列表类 function ArrayList() { this.array = []; ArrayList.prototype.insert = function (item) { this.array.push(item); } ArrayList.prototype.toString = function () { return this.array.join('-'); } ArrayList.prototype.swap = function (m, n) { var temp = this.array[m]; this.array[m] = this.array[n]; this.array[n] = temp; } // 冒泡排序 ArrayList.prototype.bubbleSort = function () { var length = this.array.length; // 比较到倒数第一个 for (var j = length - 1; j >= 0; j--) { for (var i = 0; i < j; i++) { if (this.array[i] > this.array[i + 1]) { // 交换数据 this.swap(i, i + 1); } } } } } var list = new ArrayList(); list.insert(33); list.insert(55); list.insert(2); list.insert(1); list.insert(3); list.insert(6); // alert(list.toString()); list.bubbleSort(); alert(list);
选择排序
// 选择排序 ArrayList.prototype.selectionSort = function () { var length = this.array.length; // 从0位置取数据 for (var j = 0; j < length - 1; j++) { var min = j; // 从i+1位置比较 for (var i = min + 1; i < length; i++) { if (this.array[min] > this.array[i]) { min = i; } } this.swap(min, j); } }
插入排序
// 插入排序 ArrayList.prototype.insertionSort = function() { var length = this.array.length; // 从第一个位置获取数据,向前面有序插入 for(var i = 1;i< length;i++) { var temp = this.array[i]; var j = i; while(this.array[j-1] > temp&& j>0) { this.array[j] = this.array[j-1]; j--; } // 讲j位置的数据放到temp this.array[j] = temp; } }
希尔排序
// 希尔排序 ArrayList.prototype.shellSort = function () { var length = this.array.length; var gap = Math.floor(length / 2); // 第一个默认有序 while (gap >= 1) { for (var i = gap; i < length; i++) { var temp = this.array[i]; var j = i; while (this.array[j - gap] > temp && j > gap - 1) { this.array[j] = this.array[j - gap]; j -= gap; } this.array[j] = temp; } gap = Math.floor(gap / 2); } } // 快速排序 // 选择枢纽 ArrayList.prototype.median = function (left, right) { // 1.求出中间的位置,以防有小数点,所以使用floor var center = Math.floor((left + right) / 2) // 2.判断并且进行交换 if (this.array[left] > this.array[center]) { this.swap(left, center) } if (this.array[center] > this.array[right]) { this.swap(center, right) } if (this.array[left] > this.array[right]) { this.swap(left, right) } // 3.巧妙的操作: 将center移动到right - 1的位置. // 这样方便我们循环只对左侧数据进行操作 this.swap(center, right - 1) // 4.返回枢纽 return this.array[right - 1] } // 快速排序实现 ArrayList.prototype.quickSort = function () { this.quickSortRec(0, this.array.length - 1) } ArrayList.prototype.quickSortRec = function (left, right) { // 0.递归结束条件,对比的值超出了边界值,比如下标为length或者下标为-1了 if (left >= right) return // 1.获取枢纽 var pivot = this.median(left, right) // 2.开始进行交换,保存两个对比的下标值 var i = left var j = right - 1 while (true) { // 不断改变i的值 while (this.array[++i] < pivot) { } // 不断改变j的值 while (this.array[--j] > pivot) { } // i和j表示的是下标值 if (i < j) { this.swap(i, j) } else { // 如果i>=j了表示已经溢出了,所以直接break break } } // 3.将枢纽放在正确的位置 this.swap(i, right - 1) // 4.递归调用左边 this.quickSortRec(left, i - 1) // 5.递归调用右边 this.quickSortRec(i + 1, right) }

浙公网安备 33010602011771号