Implementing a custom sorting algorithm
Implementing a sorting algorithm manually, we can use approaches like bubble sort, insertion sort, or merge sort. These algorithms compare pairs of words and swap them based on their order until the entire list is sorted.
Syntax:
function bubbleSort(wordsArray) { // ...implementation of bubble sort }
Example: In this example, we will see the use of a custom bubble sort function.
// Implementing bubble sort function
function bubbleSort(wordsArray) {
// Getting size of array
const length = wordsArray.length;
for (let i = 0; i < length - 1; i++) {
for (let j = 0; j < length - i - 1; j++) {
if (
wordsArray[j]
.localeCompare(wordsArray[j + 1], undefined, {
sensitivity: "base",
}) > 0
) {
// Swaping word in the array
const temp = wordsArray[j];
wordsArray[j] = wordsArray[j + 1];
wordsArray[j + 1] = temp;
}
}
}
return wordsArray;
}
const words = [
"JavaScript",
"Program",
"to",
"Sort",
"Words",
"in",
"Alphabetical",
"Order",
];
const sortedWords = bubbleSort(words);
// Getting the sorted array output
console.log(sortedWords);
Output
[ 'Alphabetical', 'in', 'JavaScript', 'Order', 'Program', 'Sort', 'to', 'Words' ]
JavaScript Program to Sort Words in Alphabetical Order
Sorting words in alphabetical order involves arranging them based on the standard sequence of letters in the alphabet. This process helps in organizing data, making searches efficient, and presenting information in a clear and systematic manner.