The problem below discusses a simple sorting algorithm called Bubble Sort. Let's go throw the solution:
- Create a variable totalNumberOfSwaps and make it equal to 0 at the beginning.
- we create a loop in the range of n (the size of our array).
- inside it, we generate variable numberOfSwaps represents the number of swaps for each iteration.
- inside this loop we iterate for each element of the array a to check if it is sorted ascendingly or not.
- create variable temp to make swaps of unsorted elements.
- at the end of every iteration, we increase the number of the variable numberOfSwaps by 1.
- after the loop ends, we assign the variable totalNumberOfSwaps to be its initial value and the numberOfSwaps.
- if the array a is already sorted, we exit the loop by using break key word.
- then we print the totalNumberOfSwaps and the first and the last element of the array a.
let totalNumberOfSwaps = 0
for(let i =0; i< n; i++){
let numberOfSwaps =0
for(let j =0; j< n-1; j++){
if(a[j] > a[j+1]){
let temp = a[j]
a[j] = a[j+1]
a[j+1] = temp
numberOfSwaps++
}
}
totalNumberOfSwaps = totalNumberOfSwaps + numberOfSwaps
if(numberOfSwaps == 0){
break
}
}
console.log(`Array is sorted in ${totalNumberOfSwaps} swaps.`)
console.log(`First Element: ${a[0]}`)
console.log(`Last Element: ${a[n -1]}`)