Day 20: Sorting

Day 20: Sorting

The problem below discusses a simple sorting algorithm called Bubble Sort. Let's go throw the solution:

  1. Create a variable totalNumberOfSwaps and make it equal to 0 at the beginning.
  2. we create a loop in the range of n (the size of our array).
  3. inside it, we generate variable numberOfSwaps represents the number of swaps for each iteration.
  4. inside this loop we iterate for each element of the array a to check if it is sorted ascendingly or not.
  5. create variable temp to make swaps of unsorted elements.
  6. at the end of every iteration, we increase the number of the variable numberOfSwaps by 1.
  7. after the loop ends, we assign the variable totalNumberOfSwaps to be its initial value and the numberOfSwaps.
  8. if the array a is already sorted, we exit the loop by using break key word.
  9. 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]}`)

20c3e1a2d733498884d54763c099c428gCMp5jqDhKJ6miIN-0.png