Skip to main content

How is a bubble sort algorithm implemented?

Bubble Sort Algorithm

  



Let' say we have an array,  arr[5] = {4,3,5,2,1} and when we will call the function, bubble_sort(arr, length) where length is 5, we are expecting that after it end/terminate we get a sorted array! By repetition of these three steps:


  • Step 1: Find local max
  • Step 2: Shift all the element backward after local max
  • Step 3: Assign local max


Let's see what will happen in function,

       For the 0'th iteration we have,

         0: 4,3,5,2,1

        1) we have local max (step 1) => 5
        2) we shifted all elements backward  after local max (step 2)=> 4,3,2,1,1
        3) now, assign local max (step 3) => arr[length-1] = local max (5) => 
                4,3,2,1,5

        Similarly it will carry on for further iteration,

        1: 4,3,2,1,5

        2: 3,2,1,4,5

        3: 2,1,3,4,5

        4: 1,2,3,4,5 -> sort!

       After this the function will end/terminate. 


Comments

Popular posts from this blog

Top 101 Coding Problems from Programming Job Interviews

Namaste! I'm Srijan Singh and I created this blog as my preparation for my technical interviews by completing top 101 Coding Problems. I've learned programming from opensource and I would like to do my contribution by providing my knowledge and experience to help other learners like me. I would be also creating a YouTube channel, where I would provide the explanation of the problem and solution approach. So the learners would have enough resources which will help them excel there learning and I'll provide the link of the channel below. Link to the channel  http://youtube.com/channel/UCh9WmBYS3qHrcLDg7-v37YQ?sub_confirmation=1