|
| 1 | +// Bitonic Sort is a parallel sorting algorithm that can be used to sort a sequence |
| 2 | +// of numbers in ascending or descending order. It is based on the concept of |
| 3 | +// bitonic sequences, which are sequences that first increase and then decrease |
| 4 | +// or vice versa. |
| 5 | + |
| 6 | +// Function to perform Bitonic Sort on an array |
| 7 | +function bitonicSort(arr, ascending = true) { |
| 8 | + const n = arr.length; |
| 9 | + bitonicSortRecursive(arr, 0, n, ascending); |
| 10 | +} |
| 11 | + |
| 12 | +// Function to recursively perform Bitonic Sort |
| 13 | +function bitonicSortRecursive(arr, low, count, ascending) { |
| 14 | + if (count > 1) { |
| 15 | + const k = count / 2; |
| 16 | + |
| 17 | + // Sort the first half in ascending order |
| 18 | + bitonicSortRecursive(arr, low, k, true); |
| 19 | + |
| 20 | + // Sort the second half in descending order |
| 21 | + bitonicSortRecursive(arr, low + k, k, false); |
| 22 | + |
| 23 | + // Merge the two sorted subarrays |
| 24 | + bitonicMerge(arr, low, count, ascending); |
| 25 | + } |
| 26 | +} |
| 27 | + |
| 28 | +// Function to merge two sorted subarrays in Bitonic Sort |
| 29 | +function bitonicMerge(arr, low, count, ascending) { |
| 30 | + if (count > 1) { |
| 31 | + const k = greatestPowerOfTwoLessThan(count); |
| 32 | + for (let i = low; i < low + count - k; i++) { |
| 33 | + compareAndSwap(arr, i, i + k, ascending); |
| 34 | + } |
| 35 | + bitonicMerge(arr, low, k, ascending); |
| 36 | + bitonicMerge(arr, low + k, count - k, ascending); |
| 37 | + } |
| 38 | +} |
| 39 | + |
| 40 | +// Function to find the greatest power of two less than a number |
| 41 | +function greatestPowerOfTwoLessThan(n) { |
| 42 | + let k = 1; |
| 43 | + while (k > 0 && k < n) { |
| 44 | + k = k * 2; |
| 45 | + } |
| 46 | + return k / 2; |
| 47 | +} |
| 48 | + |
| 49 | +// Function to compare and swap two elements in the array based on the sorting order |
| 50 | +function compareAndSwap(arr, i, j, ascending) { |
| 51 | + if ((arr[i] > arr[j] && ascending) || (arr[i] < arr[j] && !ascending)) { |
| 52 | + const temp = arr[i]; |
| 53 | + arr[i] = arr[j]; |
| 54 | + arr[j] = temp; |
| 55 | + } |
| 56 | +} |
| 57 | + |
| 58 | +// Example usage |
| 59 | +const arr = [3, 7, 4, 8, 6, 2, 1, 5]; |
| 60 | +console.log("Original Array:", arr); |
| 61 | + |
| 62 | +// Perform Bitonic Sort on the array in ascending order |
| 63 | +bitonicSort(arr); |
| 64 | + |
| 65 | +console.log("Bitonic-Sorted Array in Ascending Order:", arr); |
| 66 | + |
| 67 | +// Perform Bitonic Sort on the same array in descending order |
| 68 | +bitonicSort(arr, false); |
| 69 | + |
| 70 | +console.log("Bitonic-Sorted Array in Descending Order:", arr); |
0 commit comments