📘 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 how to implement a selection sort algorithm in JavaScript.
The selection sort algorithm is an in-place comparison sort algorithm. The general idea of the selection sort is to find the minimum value in the data structure, place it in the first position, then find the second minimum value, place it in the second position, and so on.
Selection Sort Algorithm in JavaScript
function selectionSort(arr) { for (var i = 0; i < arr.length; i++) { let min = i; // storing the index of minimum element for (var j = i + 1; j < arr.length; j++) { if (arr[min] > arr[ j ]) { min = j; // updating the index of minimum element } } if (i !== min) { let temp = arr[ i ]; arr[ i ] = arr[min]; arr[min] = temp; } } return arr }
Using Bubble Sort Algorithm
To test the selection sort algorithm, we can use the following code:
const array = [2,4,3,1,6,5,7,8,9]; console.log("Before selection sort - " + array); let array1 = selectionSort(array); console.log("After selection sort - "+ array1);
Output
Before selection sort - 2,4,3,1,6,5,7,8,9 After selection sort - 1,2,3,4,5,6,7,8,9
Comments
Post a Comment
Leave Comment