Bubble sort

 Bubble sort. https://www.youtube.com/watch?v=p__ETf2CKY4



We need to compare the elements in the array and send the biggest element to the end of the array.
So if we take the inner for loop mentioned in the code, it will check the first and second elements in the array. 
If the first element is greater than the second one then it will swap the elements' position in the array.
By performing the same operation again and again with other elements in the array, the biggest element in the array will be pushed to the last position in the array.

So with the inner for loop, we will push the largest number to the end position in the array.

With the outer loop, we will perform the same operation until all the numbers are sorted.


function bubbleSort(arr) {
    
    for (let i = 0; i < arr.length; i++) {
        
        for (let j = 0; j < arr.length-1-i; j++) {     
             
            if(arr[j] > arr[j+1]) {
                
                var temp = arr[j];
                
                arr[j] = arr[j+1];
                
                arr[j+1] = temp;
                
            }   
            
        }
        
    }
    
    console.log(arr);
}

bubbleSort([1,2,3,4,13,9,5,11]);


The above loop will work fine, but we are introducing a new variable in the loop. 

The variable will track if there is any swap happening or not, if there is no swap happening, then we will break the loop. 

If there is no swap happened means, the array is already sorted.

This will work effectively when we are passing already half sorted array or full sorted array to sort again.

function bubbleSort(arr) {
    var flag;
    for (let i = 0; i < arr.length; i++) {
        flag = 0;

        for (let j = 0; j < arr.length-1-i; j++) {

            if(arr[j] > arr[j+1]) {
                var temp = arr[j];
                arr[j] = arr[j+1];
                arr[j+1] = temp;
                flag = 1;
            }
            
        }
        if(flag == 0) {
            break;
        }
        
    }
    console.log(arr);
}

bubbleSort([1,2,3,4,5,6]);













Comments

Popular posts from this blog

Selection Sort

Numbers programs

Merge Sort