Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create odd_even_sort #258

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 50 additions & 0 deletions sorts/odd_even_sort
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
function oddEvenSort(inputList: number[]): number[] {
/**
* Sort input with odd-even sort.
*
* This algorithm uses the same idea of bubble sort,
* but by first dividing into two phases (odd and even).
*
* @param inputList - array of numbers to sort
* @return array sorted in ascending order
*/

let isSorted = false;
while (!isSorted) {
isSorted = true;

// Even indexed phase
for (let i = 0; i < inputList.length - 1; i += 2) {
if (inputList[i] > inputList[i + 1]) {
// Swap
[inputList[i], inputList[i + 1]] = [inputList[i + 1], inputList[i]];
isSorted = false;
}
}

// Odd indexed phase
for (let i = 1; i < inputList.length - 1; i += 2) {
if (inputList[i] > inputList[i + 1]) {
// Swap
[inputList[i], inputList[i + 1]] = [inputList[i + 1], inputList[i]];
isSorted = false;
}
}
}

return inputList;
}

// Main function to take input from user
function main() {
const input = prompt("Enter numbers to be sorted (space-separated):");
if (input) {
const inputList = input.split(" ").map(Number);
const sortedList = oddEvenSort(inputList);
console.log("The sorted list is: ", sortedList);
} else {
console.log("No input provided.");
}
}

main();