• javascript: Sorting Algorithms


    1. /**
    2. * file Sort.js
    3. * ide:vscode JavaScript Sorting Algorithms
    4. * 插件:IntelliSense,JSDoc,CodeLens,Debugger for Chrome,
    5. 静态代码检查:ESLint,JSHint,Flow Langugae Support,StandardJS-JavaScript Standard Style,
    6. koroFileHeader(文件头注释),
    7. 测试插件:Mocha sidebar,Mocha Test Explorer,Jest
    8. Path Intellisense,Import Cost,Quokka.js,Code Metrics,Javascript Booster,Turbo Console Log
    9. * https://www.programiz.com/dsa/counting-sort
    10. * https://www.geeksforgeeks.org/sorting-algorithms/
    11. * https://thedukh.com/2021/02/javascript-sorting-algorithms-explained-radix-sort/
    12. * https://www.epubit.com/
    13. * https://www.ituring.com.cn/
    14. */
    15. /**
    16. * Description placeholder 1. Bubble Sort冒泡排序法
    17. * @date 10/23/2023 - 2:47:05 PM
    18. *
    19. * @param {*} arry 需要排序的整数數組
    20. * @param {*} nszie 数组长度
    21. * @returns {*} 返回排序后结果的数组
    22. */
    23. function BubbleSort(arry, nszie)
    24. {
    25. var i, j, temp;
    26. var swapped;
    27. for (i = 0; i < nszie - 1; i++)
    28. {
    29. swapped = false;
    30. for (j = 0; j < nszie - i - 1; j++)
    31. {
    32. if (arry[j] > arry[j + 1])
    33. {
    34. // Swap arry[j] and arry[j+1]
    35. temp = arry[j];
    36. arry[j] = arry[j + 1];
    37. arry[j + 1] = temp;
    38. swapped = true;
    39. }
    40. }
    41. // IF no two elements were
    42. // swapped by inner loop, then break
    43. if (swapped == false)
    44. break;
    45. }
    46. return arry
    47. }
    48. /**
    49. * 交换操作
    50. * @param {*} arry 数组
    51. * @param {*} xp
    52. * @param {*} yp
    53. */
    54. function swap(arry,xp, yp)
    55. {
    56. var temp = arry[xp];
    57. arry[xp] = arry[yp];
    58. arry[yp] = temp;
    59. }
    60. /**
    61. * 2 选择排序 Selection Sort
    62. * @param {*} arry 需要排序的整数數組
    63. * @param {*} nsize 数组长度
    64. * @returns 返回排序后结果的数组
    65. */
    66. function SelectionSort(arry, nsize)
    67. {
    68. var i, j, min_idx;
    69. // One by one move boundary of unsorted subarray
    70. for (i = 0; i < nsize-1; i++)
    71. {
    72. // Find the minimum element in unsorted array
    73. min_idx = i;
    74. for (j = i + 1; j < nsize; j++)
    75. if (arry[j] < arry[min_idx])
    76. min_idx = j;
    77. // Swap the found minimum element with the first element
    78. swap(arry,min_idx, i);
    79. }
    80. return arry;
    81. }
    82. /**
    83. * 3 插入排序 Insertion Sort
    84. * @param {*} arry 需要排序的整数數組
    85. * @param {*} nsize 数组长度
    86. * @returns 返回排序后结果的数组
    87. */
    88. function InsertionSort(arry, nsize)
    89. {
    90. let i, key, j;
    91. for (i = 1; i < nsize; i++)
    92. {
    93. key = arry[i];
    94. j = i - 1;
    95. /* Move elements of arr[0..i-1], that are
    96. greater than key, to one position ahead
    97. of their current position */
    98. while (j >= 0 && arry[j] > key)
    99. {
    100. arry[j + 1] = arry[j];
    101. j = j - 1;
    102. }
    103. arry[j + 1] = key;
    104. }
    105. return arry;
    106. }
    107. /**
    108. * 整数数组转字符串显示
    109. * @param {*} arry 需要打印的数组
    110. * @param {*} nsize 数组的长度
    111. *
    112. * @returns 返回打印格式字符串
    113. */
    114. function stringArray(arry, nsize)
    115. {
    116. var myStr=new Array();
    117. var i;
    118. for (i = 0; i < nsize; i++)
    119. {
    120. //getstr=getstr+arry[i].toString() + "
      ";
    121. myStr[i]=arry[i];
    122. console.log(arry[i]);
    123. }
    124. console.log(myStr.join("
      "
      ));
    125. return myStr.join("
      "
      );
    126. //console.log(arry);
    127. /* var myStr=new Array();
    128. var getstr="";
    129. */
    130. /*
    131. var i;
    132. for (i = 0; i < nsize; i++)
    133. {
    134. getstr=getstr+arry[i] + " ";
    135. myStr[i]=arry[i].toString();
    136. console.log(myStr[i]);
    137. }
    138. return getstr;//myStr.join(" ");*/
    139. }
    140. //
    141. // Merges two subarrays of arr[].
    142. // First subarray is arr[l..m]
    143. // Second subarray is arr[m+1..r]
    144. /**
    145. *
    146. * @param {*} arry 需要打印的数组
    147. * @param {*} indexStart
    148. * @param {*} m
    149. * @param {*} indexEnd
    150. */
    151. function merge(arry, indexStart, m, indexEnd)
    152. {
    153. var n1 = m - indexStart + 1;
    154. var n2 = indexEnd - m;
    155. // Create temp arrays
    156. var L = new Array(n1);
    157. var R = new Array(n2);
    158. // Copy data to temp arrays L[] and R[]
    159. for (var i = 0; i < n1; i++)
    160. L[i] = arry[indexStart + i];
    161. for (var j = 0; j < n2; j++)
    162. R[j] = arry[m + 1 + j];
    163. // Merge the temp arrays back into arry[l..r]
    164. // Initial index of first subarray
    165. var i = 0;
    166. // Initial index of second subarray
    167. var j = 0;
    168. // Initial index of merged subarray
    169. var k = indexStart;
    170. while (i < n1 && j < n2) {
    171. if (L[i] <= R[j]) {
    172. arry[k] = L[i];
    173. i++;
    174. }
    175. else {
    176. arry[k] = R[j];
    177. j++;
    178. }
    179. k++;
    180. }
    181. // Copy the remaining elements of
    182. // L[], if there are any
    183. while (i < n1) {
    184. arry[k] = L[i];
    185. i++;
    186. k++;
    187. }
    188. // Copy the remaining elements of
    189. // R[], if there are any
    190. while (j < n2) {
    191. arry[k] = R[j];
    192. j++;
    193. k++;
    194. }
    195. }
    196. // l is for left index and r is
    197. // right index of the sub-array
    198. // of arr to be sorted
    199. /**
    200. * 4 合并排序 Merge Sort
    201. * @param {*} arry 需要排序的整数數組
    202. * @param {*} indexStart 数组索引值 0
    203. * @param {*} indexEnd 索引值最大值 数组长度-1
    204. * @returns 返回排序好的数组
    205. */
    206. function mergeSort(arry,indexStart, indexEnd){
    207. if(indexStart>=indexEnd){
    208. return;
    209. }
    210. var m =indexStart+ parseInt((indexEnd-indexStart)/2);
    211. mergeSort(arry,indexStart,m);
    212. mergeSort(arry,m+1,indexEnd);
    213. merge(arry,indexStart,m,indexEnd);
    214. return arry;
    215. }
    216. /**
    217. * Function to partition the array and return the partition index
    218. * @param {*} arry 需要排序的整数數組
    219. * @param {*} low 数组索引值 0
    220. * @param {*} high 索引值最大值 数组长度-1
    221. * @returns
    222. */
    223. function quickPartition(arry, low, high) {
    224. // Choosing the pivot
    225. let pivot = arry[high];
    226. // Index of smaller element and indicates the right position of pivot found so far
    227. let i = low - 1;
    228. for (let j = low; j <= high - 1; j++) {
    229. // If current element is smaller than the pivot
    230. if (arry[j] < pivot) {
    231. // Increment index of smaller element
    232. i++;
    233. [arry[i], arry[j]] = [arry[j], arry[i]]; // Swap elements
    234. }
    235. }
    236. [arry[i + 1], arry[high]] = [arry[high], arry[i + 1]]; // Swap pivot to its correct position
    237. return i + 1; // Return the partition index
    238. }
    239. /**
    240. * The main function that implements QuickSort
    241. * 5 Quick Sort 快速排序
    242. * @param {*} arry 需要排序的整数數組
    243. * @param {*} low 数组索引值 0
    244. * @param {*} high 索引值最大值 数组长度-1
    245. * @returns 返回排序好的数组
    246. */
    247. function quickSort(arry, low, high) {
    248. if (low < high) {
    249. // pi is the partitioning index, arr[pi] is now at the right place
    250. let pi = quickPartition(arry, low, high);
    251. // Separately sort elements before partition and after partition
    252. quickSort(arry, low, pi - 1);
    253. quickSort(arry, pi + 1, high);
    254. }
    255. return arry;
    256. }
    257. /**
    258. * of Heap Sort
    259. * 6 堆排序 Heap Sort
    260. * @param {*} arry 需要排序的整数數組
    261. * @returns 返回排序好的数组
    262. */
    263. function heapSort( arry)
    264. {
    265. var N = arry.length;
    266. // Build heap (rearrange array)
    267. for (var i = Math.floor(N / 2) - 1; i >= 0; i--)
    268. heapify(arry, N, i);
    269. // One by one extract an element from heap
    270. for (var i = N - 1; i > 0; i--) {
    271. // Move current root to end
    272. var temp = arry[0];
    273. arry[0] = arry[i];
    274. arry[i] = temp;
    275. // call max heapify on the reduced heap
    276. heapify(arry, i, 0);
    277. }
    278. return arry;
    279. }
    280. /**
    281. * To heapify a subtree rooted with node i which is
    282. * an index in arr[]. n is size of heap
    283. * @param {*} arry 需要排序的整数數組
    284. * @param {*} N 数组长度
    285. * @param {*} i 数组索引值 0
    286. */
    287. function heapify(arry, N, i)
    288. {
    289. var largest = i; // Initialize largest as root
    290. var l = 2 * i + 1; // left = 2*i + 1
    291. var r = 2 * i + 2; // right = 2*i + 2
    292. // If left child is larger than root
    293. if (l < N && arry[l] > arry[largest])
    294. largest = l;
    295. // If right child is larger than largest so far
    296. if (r < N && arry[r] > arry[largest])
    297. largest = r;
    298. // If largest is not root
    299. if (largest != i) {
    300. var swap = arry[i];
    301. arry[i] = arry[largest];
    302. arry[largest] = swap;
    303. // Recursively heapify the affected sub-tree
    304. heapify(arry, N, largest);
    305. }
    306. }
    307. /**
    308. * 7 Counting Sort 计数排序
    309. * @param {*} arry 需要排序的整数數組
    310. * @param {*} min 数组中最小的值
    311. * @param {*} max 数组中最大的值
    312. * @returns 返回排序好的数组
    313. */
    314. function countingSort(arry, min, max) {
    315. let j = 0;
    316. let supplementary = [];
    317. for (let i = min; i <= max; i++) {
    318. supplementary[i] = 0;
    319. }
    320. for (let i=0; i < arry.length; i++) {
    321. supplementary[arry[i]] += 1;
    322. }
    323. for (let i = min; i <= max; i++) {
    324. while (supplementary[i] > 0) {
    325. arry[j++] = i;
    326. supplementary[i] -= 1;
    327. }
    328. }
    329. return arry;
    330. }
    331. /**
    332. * 7 Counting Sort 计数排序
    333. * @param {*} arry 需要排序的整数數組
    334. * @returns 返回排序好的数组
    335. */
    336. function duCountingSort(arry) {
    337. let j = 0;
    338. let supplementary = [];
    339. min=getArrayMin(arry);
    340. max=getArrayMax(arry);
    341. for (let i = min; i <= max; i++) {
    342. supplementary[i] = 0;
    343. }
    344. for (let i=0; i < arry.length; i++) {
    345. supplementary[arry[i]] += 1;
    346. }
    347. for (let i = min; i <= max; i++) {
    348. while (supplementary[i] > 0) {
    349. arry[j++] = i;
    350. supplementary[i] -= 1;
    351. }
    352. }
    353. return arry;
    354. }
    355. /**
    356. * 求得数组中最大值
    357. * @param {*} arry 整数數組
    358. * @param {*} nszie 数组长度
    359. * @returns 返回数组中的最大值
    360. */
    361. function getMax(arry,nszie)
    362. {
    363. let mx = arry[0];
    364. for (let i = 1; i < nszie; i++)
    365. if (arry[i] > mx)
    366. mx = arry[i];
    367. return mx;
    368. }
    369. /**
    370. * 求得数组中最小值
    371. * @param {*} arry 整数數組
    372. * @returns 返回数组中的最小值
    373. */
    374. function getArrayMin(arry){
    375. var min = arry[0];
    376. for(var i = 1, ilen = arry.length; i < ilen; i+=1) {
    377. if(arry[i] < min) {
    378. min = arry[i];
    379. }
    380. }
    381. return min;
    382. }
    383. /**
    384. * 求得数组中最大值
    385. * @param {*} arry 整数數組
    386. * @returns 返回数组中的最大值
    387. */
    388. function getArrayMax(arry) {
    389. var max = arry[0];
    390. for(var i = 1,ilen = arry.length; i < ilen; i++) {
    391. if(arry[i] > max) {
    392. max = arry[i];
    393. }
    394. }
    395. return max;
    396. }
    397. /**
    398. *
    399. * @param {*} arry
    400. * @param {*} nszie
    401. * @param {*} exp
    402. */
    403. function radixCountSort(arry,nszie,exp)
    404. {
    405. let output = new Array(nszie); // output array
    406. let i;
    407. let x;
    408. let count = new Array(10);
    409. for(let i=0;i<10;i++)
    410. count[i]=0;
    411. // Store count of occurrences in count[] 这里有问题
    412. for (i = 0; i < nszie; i++)
    413. {
    414. let s=arry[i]/exp;
    415. x = Math.floor(s) % 10;
    416. }
    417. count[x]++;
    418. // Change count[i] so that count[i] now contains
    419. // actual position of this digit in output[]
    420. for (i = 1; i < 10; i++)
    421. count[i] += count[i - 1];
    422. // Build the output array
    423. for (i = nszie - 1; i >= 0; i--) {
    424. output[count[x] - 1] = arry[i];
    425. count[x]--;
    426. }
    427. // Copy the output array to arr[], so that arr[] now
    428. // contains sorted numbers according to current digit
    429. for (i = 0; i < nszie; i++)
    430. arry[i] = output[i];
    431. }
    432. /**
    433. * The main function to that sorts arr[] of size n using
    434. 8 Radix Sort 基数排序 Radix Sort 有问题
    435. * @param {*} arry 需要排序的整数數組
    436. * @param {*} nszie 数组长度
    437. */
    438. function radixsort(arry,nszie)
    439. {
    440. // Find the maximum number to know number of digits
    441. let m = getMax(arry, nszie);
    442. // Do counting sort for every digit. Note that
    443. // instead of passing digit number, exp is passed.
    444. // exp is 10^i where i is current digit number
    445. for (let exp = 1; Math.floor(m / exp) > 0; exp *= 10)
    446. radixCountSort(arry, nszie, exp);
    447. return arry;
    448. }
    449. /**
    450. *
    451. * @param {*} arry
    452. * @returns
    453. */
    454. function getBiggestDigitCount(arry) {
    455. let maxDigits = 0;
    456. for (let i = 0; i < arry.length; i++) {
    457. maxDigits = Math.max(maxDigits, arry[i].toString().length);
    458. }
    459. return maxDigits;
    460. }
    461. /**
    462. *
    463. * @param {*} arry
    464. * @param {*} i
    465. * @returns
    466. */
    467. function getDigitAtPlace(arry, i) {
    468. return arry.toString().split("").reverse()[i] || 0;
    469. }
    470. /**
    471. * 8 Radix Sort 基数排序
    472. * @param {*} arry 需要排序的整数數組
    473. * @returns 返回排序后结果的数组
    474. */
    475. function DuRadixSort(arry) {
    476. let maxDigits = getBiggestDigitCount(arry);
    477. for (let i = 0; i < maxDigits; i++) {
    478. let bucketArray = Array.from({ length: 10 }, () => []);
    479. for (let j = 0; j < arry.length; j++) {
    480. let digit = getDigitAtPlace(arry[j], i);
    481. bucketArray[digit].push(arry[j]);
    482. }
    483. arry = [].concat(...bucketArray);
    484. }
    485. return arry;
    486. }
    487. /**
    488. * 9. Bucket Sort 桶排序
    489. * using bucket sort
    490. * @param {*} arry 需要排序的整数數組
    491. * @param {*} nszie 数组长度
    492. * @returns 返回排序后结果的数组
    493. */
    494. function bucketSort(arry,nszie)
    495. {
    496. if (nszie <= 0)
    497. return;
    498. // 1) Create n empty buckets
    499. let buckets = new Array(nszie);
    500. for (let i = 0; i < nszie; i++)
    501. {
    502. buckets[i] = [];
    503. }
    504. // 2) Put array elements in different buckets
    505. for (let i = 0; i < nszie; i++) {
    506. let idx = arry[i] * nszie;
    507. let flr = Math.floor(idx);
    508. //buckets[flr].push(arry[i]); //有问题
    509. buckets[flr].push(arry[i]);
    510. }
    511. // 3) Sort individual buckets
    512. for (let i = 0; i < nszie; i++) {
    513. buckets[i].sort(function(a,b){return a-b;});
    514. }
    515. // 4) Concatenate all buckets into arr[]
    516. let index = 0;
    517. for (let i = 0; i < nszie; i++) {
    518. for (let j = 0; j < buckets[i].length; j++) {
    519. arry[index++] = buckets[i][j];
    520. }
    521. }
    522. return arry;
    523. }
    524. /**
    525. * 9. Bucket Sort 桶排序
    526. * @param {*} arry 需要排序的整数數組
    527. * @returns 返回排序后结果的数组
    528. */
    529. function duBubbleSort(arry) {
    530. let swapHappened;
    531. for (let i = arry.length; i > 0; i--) {
    532. swapHappened = true;
    533. for (let j = 0; j < i - 1; j++) {
    534. if (arry[j] > arry[j + 1]) {
    535. [arry[j], arry[j + 1]] = [arry[j + 1], arry[j]];
    536. swapHappened = false;
    537. }
    538. }
    539. if (swapHappened) {
    540. break;
    541. }
    542. }
    543. return arry;
    544. }
    545. /**
    546. *
    547. * @param {*} arry
    548. * @returns
    549. */
    550. function bingoSort(arry) {
    551. let n=arry.length;
    552. let bingo = arry[0];
    553. let nextBingo = arry[0];
    554. // For finding the maximum and minimum element of
    555. // the Array
    556. for (let i = 1; i < n; bingo = Math.min(bingo, arry[i]), nextBingo = Math.max(nextBingo, arry[i]), i++)
    557. ;
    558. let largestEle = nextBingo;
    559. let nextElePos = 0;
    560. while (bingo < nextBingo)
    561. {
    562. // Will keep the track of the element position to
    563. // shifted to their correct position
    564. let startPos = nextElePos;
    565. for (let i = startPos; i < n; i++) {
    566. if (arry[i] == bingo) {
    567. [arry[i], arry[nextElePos]] = [arry[nextElePos], arry[i]];
    568. nextElePos = nextElePos + 1;
    569. }
    570. // Here we are finding the next Bingo Element
    571. // for the next pass
    572. else if (arry[i] < nextBingo)
    573. nextBingo = arry[i];
    574. }
    575. bingo = nextBingo;
    576. nextBingo = largestEle;
    577. }
    578. for (let i = 0; i < arry.length; i++) {
    579. // console.log("arr: ",arry[i]);
    580. }
    581. return arry;
    582. }
    583. /**
    584. * 打印数组
    585. * @param {*} arry 需要找印的数组
    586. * @param {*} nsize 数组长度
    587. * @returns 返回打印的格式字符串
    588. */
    589. function printArray(arry, nsize)
    590. {
    591. var getstr="";
    592. var i;
    593. for (i = 0; i < nsize; i++)
    594. {
    595. console.log(arry[i] + " ");
    596. getstr=getstr+arry[i]+" ";
    597. }
    598. return getstr;
    599. }

    调用:

    1. 成长开始,geovindu,涂聚文,Geovin Du Bubble Sort冒泡排序法

    输出:

  • 相关阅读:
    后缀表达式求值
    torch.expand()函数用法
    SpringCloud溯源——从单体架构到微服务Microservices架构 & 分布式和微服务 & 为啥要用微服务
    关于#网络#的问题:采用CRC方法进行校验,求数据冗余码FCS(相关搜索:计算机网络)
    javascript开发经验小结
    力扣(122.1049)补7.29
    为什么说 ICMP 协议是网络最强辅助
    MySQL | 存储《康师傅MySQL从入门到高级》笔记
    RTL8720DN开发笔记一 环境搭建与mqtt实例
    【医学分割】Medical Image Segmentation Using Deep Learning: A Survey
  • 原文地址:https://blog.csdn.net/geovindu/article/details/134002838