- vừa được xem lúc

Blog#85: Bubble Up to the Top: A Beginner's Guide to Bubble Sort in JavaScript

0 0 12

Người đăng: NGUYỄN ANH TUẤN

Theo Viblo Asia

Hi, I'm Tuan, a Full-stack Web Developer from Tokyo 😊. Follow my blog to not miss out on useful and interesting articles in the future.

As a beginner programmer, you may have heard of the term "sorting algorithms" but have no idea what they are or how they work. Well, fear not! In this article, we'll be diving into one of the most basic sorting algorithms out there: bubble sort.

But before we get into the nitty-gritty of how bubble sort works, let's first define what it is. Simply put, bubble sort is an algorithm that compares adjacent elements in an array and swaps their positions if they are not in the correct order. It continues to do this until the array is fully sorted.

Now that we have a basic understanding of bubble sort, let's take a look at how it works with an example. Let's say we have an array of numbers that we want to sort from least to greatest: [5, 2, 1, 4, 3].

Using bubble sort, we would first compare the first two elements, 5 and 2. Since 5 is greater than 2, we would swap their positions. The array would now look like this: [2, 5, 1, 4, 3].

Next, we would compare the second and third elements, 5 and 1. Since 5 is greater than 1, we would swap their positions. The array would now look like this: [2, 1, 5, 4, 3].

We would continue this process until we reach the end of the array. The final step would be comparing the fourth and fifth elements, 4 and 3. Since 4 is greater than 3, we would swap their positions. The final, sorted array would look like this: [1, 2, 3, 4, 5].

So, now that you have a better understanding of how bubble sort works, let's take a look at some real-world use cases for this algorithm in JavaScript with a functional-oriented approach.

Example

Sorting a list of names alphabetically

const sortNames = names => { for (let i = 0; i < names.length; i++) { for (let j = 0; j < names.length - i - 1; j++) { if (names[j] > names[j + 1]) { // Swap names[j] and names[j + 1] let temp = names[j]; names[j] = names[j + 1]; names[j + 1] = temp; } } } return names;
}; const names = ['John', 'Bob', 'Sue', 'Alice', 'Zack'];
console.log(sortNames(names)); // ['Alice', 'Bob', 'John', 'Sue', 'Zack']

Sorting a list of numbers from least to greatest

const sortNumbers = numbers => { for (let i = 0; i < numbers.length; i++) { for (let j = 0; j < numbers.length - i - 1; j++) { if (numbers[j] > numbers[j + 1]) { // Swap numbers[j] and numbers[j + 1] let temp = numbers[j]; numbers[j] = numbers[j + 1]; numbers[j + 1] = temp; } } } return numbers;
};

Sorting a list of products by price

const sortProducts = products => { for (let i = 0; i < products.length; i++) { for (let j = 0; j < products.length - i - 1; j++) { if (products[j].price > products[j + 1].price) { // Swap products[j] and products[j + 1] let temp = products[j]; products[j] = products[j + 1]; products[j + 1] = temp; } } } return products;
}; const products = [ { name: 'Product A', price: 9.99 }, { name: 'Product B', price: 7.99 }, { name: 'Product C', price: 12.99 }];
console.log(sortProducts(products));
// [{ name: 'Product B', price: 7.99 }, { name: 'Product A', price: 9.99 }, { name: 'Product C', price: 12.99 }]

Sorting a list of employees by their job titles

const sortEmployees = (employees) => { for (let i = 0; i < employees.length; i++) { for (let j = 0; j < employees.length - i - 1; j++) { if (employees[j].jobTitle > employees[j + 1].jobTitle) { // Swap employees[j] and employees[j + 1] let temp = employees[j]; employees[j] = employees[j + 1]; employees[j + 1] = temp; } } } return employees;
}; const employees = [ { name: "John", jobTitle: "Manager" }, { name: "Sue", jobTitle: "Developer" }, { name: "Alice", jobTitle: "Designer" }, { name: "Bob", jobTitle: "Salesperson" },
];
console.log(sortEmployees(employees)); // [
// { name: 'Alice', jobTitle: 'Designer' },
// { name: 'Sue', jobTitle: 'Developer' },
// { name: 'John', jobTitle: 'Manager' },
// { name: 'Bob', jobTitle: 'Salesperson' }
// ]

Sorting a list of cities by their population

const sortCities = (cities) => { for (let i = 0; i < cities.length; i++) { for (let j = 0; j < cities.length - i - 1; j++) { if (cities[j].population > cities[j + 1].population) { // Swap cities[j] and cities[j + 1] let temp = cities[j]; cities[j] = cities[j + 1]; cities[j + 1] = temp; } } } return cities;
}; const cities = [ { name: "New York", population: 8175133 }, { name: "Los Angeles", population: 3792621 }, { name: "Chicago", population: 2695598 }, { name: "Houston", population: 2130332 },
];
console.log(sortCities(cities)); // [
// { name: 'Houston', population: 2130332 },
// { name: 'Chicago', population: 2695598 },
// { name: 'Los Angeles', population: 3792621 },
// { name: 'New York', population: 8175133 }
// ]

Performance and Limitations of Bubble Sort

Now that we've seen some practical examples of using bubble sort in JavaScript, let's talk about the performance and limitations of this algorithm.

One of the main limitations of bubble sort is its time complexity. Specifically, bubble sort has a time complexity of O(n^2), meaning that it becomes increasingly slower as the size of the input increases. This makes it a less efficient option for sorting large lists.

However, bubble sort does have some benefits. It is a simple and easy-to-understand algorithm, making it a good choice for beginners. It is also a stable sort, meaning that it preserves the relative order of elements with equal keys.

Conclusion

In conclusion, bubble sort is a simple and easy-to-understand algorithm that can be useful for sorting small lists. While it is not the most efficient algorithm for larger lists, it can still be a useful tool in certain situations. Remember to keep its time complexity in mind when deciding whether or not to use bubble sort for your sorting needs.

As always, I hope you enjoyed this article and learned something new. Thank you and see you in the next articles!

If you liked this article, please give me a like and subscribe to support me. Thank you. 😊

Ref

Bình luận

Bài viết tương tự

- vừa được xem lúc

Giới thiệu Typescript - Sự khác nhau giữa Typescript và Javascript

Typescript là gì. TypeScript là một ngôn ngữ giúp cung cấp quy mô lớn hơn so với JavaScript.

0 0 500

- vừa được xem lúc

Bạn đã biết các tips này khi làm việc với chuỗi trong JavaScript chưa ?

Hi xin chào các bạn, tiếp tục chuỗi chủ đề về cái thằng JavaScript này, hôm nay mình sẽ giới thiệu cho các bạn một số thủ thuật hay ho khi làm việc với chuỗi trong JavaScript có thể bạn đã hoặc chưa từng dùng. Cụ thể như nào thì hãy cùng mình tìm hiểu trong bài viết này nhé (go).

0 0 414

- vừa được xem lúc

Một số phương thức với object trong Javascript

Trong Javascript có hỗ trợ các loại dữ liệu cơ bản là giống với hầu hết những ngôn ngữ lập trình khác. Bài viết này mình sẽ giới thiệu về Object và một số phương thức thường dùng với nó.

0 0 136

- vừa được xem lúc

Tìm hiểu về thư viện axios

Giới thiệu. Axios là gì? Axios là một thư viện HTTP Client dựa trên Promise.

0 0 117

- vừa được xem lúc

Imports và Exports trong JavaScript ES6

. Giới thiệu. ES6 cung cấp cho chúng ta import (nhập), export (xuất) các functions, biến từ module này sang module khác và sử dụng nó trong các file khác.

0 0 93

- vừa được xem lúc

Bài toán đọc số thành chữ (phần 2) - Hoàn chỉnh chương trình dưới 100 dòng code

Tiếp tục bài viết còn dang dở ở phần trước Phân tích bài toán đọc số thành chữ (phần 1) - Phân tích đề và những mảnh ghép đầu tiên. Bạn nào chưa đọc thì có thể xem ở link trên trước nhé.

0 0 229