Search This Blog

2024/04/08

Javascript Algorithm: Odd-Even Sort / Brick Sort


 Odd-Even Sort / Brick Sort:
Odd-Even Sort is basically a variation of bubble-sort. This algorithm is
divided into two phases- Odd and Even Phase. The algorithm runs until the
array elements are sorted and in each iteration two phases occurs- Odd and
Even Phases. In the odd phase, we perform a bubble sort on odd indexed
elements and in the even phase, we perform a bubble sort on even indexed
elements.
Javascript Implementation:
function oddEvenSort(arr, n) {
// Perform Bubble sort on odd indexed elements & even indexed elements

let isSwapped = true;

while (isSwapped == true) {
isSwapped =false;

// i will be 1,3 and n-2 is 2
for (let i = 1; i <= n - 2; i = i + 2) {
if (arr[i] > arr[i + 1]) {
//swap
[arr[i], arr[i + 1]] = [arr[i + 1], arr[i]];
isSwapped = true;
}
}

// i will be 0,2 and n-2 is 2
for (let i = 0; i <= n - 2; i = i + 2) {
if (arr[i] > arr[i + 1]) {
//swap
[arr[i], arr[i + 1]] = [arr[i + 1], arr[i]];
isSwapped = true;
}
}
}

return arr;
}

let arr = [100, 67, -6, 8];
console.log("Input Array:", arr);
let result = oddEvenSort(arr, arr.length);
console.log("Result:", result);

Output:
Input Array: [ 100, 67, -6, 8 ]
Result: [ -6, 8, 67, 100 ]

Note:
Time Complexity : O(N2) where, N = Number of elements in the input array.

No comments:

Post a Comment