📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.
🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (176K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
Here we will learn a simple sorting algorithm that is bubble sort. It is the simplest of all the sorting algorithms.
The bubble sort algorithm compares every two adjacent items and swaps them if the first one is bigger than the second one. It has this name because the items tend to move up into the correct order, like bubbles rising to the surface.
Bubble Sort Algorithm in JavaScript
function bubbleSort(array) { const length = array.length; for (let i = 0; i < length; i++) { for (let j = 0; j < length - 1; j++) { if (array[j] > array[j + 1]) { swap(array, j, j + 1); } } } return array; } function swap(array, a, b) { const temp = array[a]; array[a] = array[b]; array[b] = temp; }
Using Bubble Sort Algorithm
const array1 = [2, 1, 3, 7, 6, 5]; const array2 = bubbleSort(array1); console.log(array2);
Output
[1, 2, 3, 5, 6, 7]
Comments
Post a Comment
Leave Comment