From 167bb9f481f3505fdaa611fa73eb56fa1fd4c25b Mon Sep 17 00:00:00 2001 From: yigencong Date: Wed, 21 Feb 2024 21:36:34 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E6=B7=BB=E5=8A=A0=E9=B8=A1=E5=B0=BE?= =?UTF-8?q?=E9=85=92=E6=8E=92=E5=BA=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- sort/bubble-sort-test.mjs | 15 ++++++++++----- sort/bubble-sort.mjs | 24 ++++++++++++++++++++++++ 2 files changed, 34 insertions(+), 5 deletions(-) diff --git a/sort/bubble-sort-test.mjs b/sort/bubble-sort-test.mjs index d5c32e1..96f71a2 100644 --- a/sort/bubble-sort-test.mjs +++ b/sort/bubble-sort-test.mjs @@ -1,10 +1,15 @@ import {generateRandomArray, measureTime} from "../util/index.mjs" -import { bubbleSort, bubbleSort2, bubbleSort3 } from "./bubble-sort.mjs" +import { bubbleSort, bubbleSort2, bubbleSort3, cocktailSort } from "./bubble-sort.mjs" const arr = generateRandomArray(10000) const arr2 = generateRandomArray(10000) -const arr3 = generateRandomArray(10000) -measureTime(bubbleSort, arr) -measureTime(bubbleSort2, arr2) -measureTime(bubbleSort3, arr3) +// const arr3 = generateRandomArray(10000) +// measureTime(bubbleSort, arr) +// measureTime(bubbleSort2, arr2) +// measureTime(bubbleSort3, arr3) + + +// 鸡尾酒排序测试 +measureTime(cocktailSort, arr) +measureTime(bubbleSort, arr2) \ No newline at end of file diff --git a/sort/bubble-sort.mjs b/sort/bubble-sort.mjs index 810a0ba..0e5a1f2 100644 --- a/sort/bubble-sort.mjs +++ b/sort/bubble-sort.mjs @@ -46,3 +46,27 @@ export function bubbleSort3(arr) { k = swapPos // 把最后一次交换的位置给k,之后的排序支队1 - n-k的元素进行比较,因为之后的元素都是有序的 } } + +// 鸡尾酒排序(冒泡排序变形) +export function cocktailSort(arr) { + let left = 0, right = arr.length - 1, index; + while(left < right) { + // 大的排在后面 + for (let i = left;i < right;i++) { + if (arr[i] > arr[i+1]) { + swap(arr, i, i+1) + index = i + } + } + // 第一轮排完之后index右侧的数字都是有序的,只需从index开始排就行(重点) + right = index + // 小的排前面 + for (let i = right;i > left;i--) { + if (arr[i] < arr[i-1]) { + swap(arr, i, i-1) + index = i + } + } + left = index + } +}