What is Bubble sort exactly is ?

Bubble sort  algorithm 

 
  • Bubble sort is a very simple and very  easy to implement  sorting technique
  • Default arrange in  ascending order 

logic 


let's take an example, an example, we have a list of numbers stored in array 

                                                                 
                  
logic start with comparison of first two element and if the left element is greater than right element they swap their position  Comparison proceeds till the end of array 


logical illustration 






ALGORITHM 



Modified ALGORITHM :-

  • Bubble_Sort(A,N): A is array of values and N is the number of element   
  1. Repeat step 2,3,&4 for round =1,2,3,....N-1
  2. Flag=0,
  3. Repeat for i=0,1,2...N-1-round                                                                                                                                                                        If A[i] >A [i+1] then swap A[i] and A[i+1],also set flag=1
  4. if flag ==0  return
  5.  return  

  

 complexity O(n^2)
Worst complexity: n^2
Average complexity: n^2
Best complexity: n
Space complexity: 1

complexity for modified algorithm  O(n) 

   code 



function bubble_sort(arr) {

let round, temp;
for (round = 1; round <= arr.length - 1; round++) {
  let flag = 0;
  for (let i = 0; i <= (arr.length - 1) - round; i++) {
    if (arr[i] > arr[i + 1]) {
      flag = 1
      temp = arr[i];
      arr[i] = arr[i + 1];
      arr[i + 1] = temp;
    }
  }
  if (flag === 0) {
    console.log('total no of round' + ' ' + round)
    return arr;
    }
  }
//console.log(arr +" "+ arr.length)
return arr

}

//console.log(bubble_sort([9,11,24,36,48,59,65,79,88]))









Comments

Popular posts from this blog

Difficulty in Learning Programming Languages? Follow these guided steps

WHAT IS INSERTION SORT ?

Why coding and programming are in trend and what's the difference?