Reputation: 1
As we all know that selection sort in DS is done by comparing the elements and then swapping the smallest to the beginning using a temporary variable. I have learnt a new way to swap is by just changing the array positions. I need your view and suggestions that if it effects the overall performance of the function or we should follow the traditional way.
the traditional way of sorting the array using selection sort is
const fun = (arr) => {
console.log(arr)
for (let i = 0; i < arr.length; i++) {
let min = i
for (let j = i + 1; j < arr.length; j++)//1
{
if (arr[j] < arr[min]) {
min = j;
}
let temp = arr[i]
arr[i] = arr[min]
arr[min] = temp
}
} return arr
}
console.log(fun([23, 564, 4, 34, 45, 7, 56, 878, 5, 1]))
the way i tried is below
const fun = (arr) => {
console.log(arr)
for (let i = 0; i < arr.length; i++) {
for (let j = i + 1; j < arr.length; j++)//1
{
if (arr[j] < arr[i]) {
[arr[i], arr[j]] = [arr[j], arr[i]] // here I swapped the array elements **
}
}
} return arr
}
console.log(fun([23, 4, 34, 7, 56, 878, 5, 1]))
Upvotes: 0
Views: 12