Implement Bubble Sort using JavaScript

If you’re in a computer science background, widening your technical horizons is the best thing you should do. However, your programming skills matter the most and one must continuously keep sharpening these skills. And to become a better programmer in the future. Though there are multiple things to focus on, one specific area you must focus on is the world of data structures. Data structures in general are specific approaches to solve problems in such a way that computer resources get used minimum. In general, there are multiple data structures you can learn and implement as well. However, to keep things simple were going to start with some basic programs you must learn before moving on to complex algorithms. Therefore today we’re going to learn how to Implement Bubble Sort using Javascript.

 

What is Bubble Sort?

 

  • Comes in the list of simplest data structures, Bubble Sort is the way of arranging elements in ascending order. The array is either sorted or is unsorted.

 

  • Works by comparing adjacent elements in an array and swapping them, if required. This process continues till each element in an array gets sorted.

 

What’s The Approach?

 

  • Consider array, arr[n] of size n we want to implement Bubble Sort on. So firstly we’ll iterate a for loop, with an iterative variable i from 0 to n-1.

 

 

  • we’ll compare the element at iterating index with its next element from the array. If the comparing element is smaller, we’ll swap the elements.

 

Also Read: How To Print Hello World in JavaScript

 

Javascript Program To Implement Bubble Sort

 

Input:

 

64, 34, 25, 12, 22, 11, 90

 

Output:

 

Sorted array:

11 12 22 25 34 64 90

 

<script>

//Function to swap Integers
function swap(arr, xp, yp)
{
    var temp = arr[xp];
    arr[xp] = arr[yp];
    arr[yp] = temp;
}

// An optimized version of Bubble Sort
function bubbleSort( arr, n)
{
var i, j;
for (i = 0; i < n-1; i++)
{
    for (j = 0; j < n-i-1; j++)
    {
        if (arr[j] > arr[j+1])
        {
        swap(arr,j,j+1);
        
        }
    }

}
}

/* Function to print an array */
function printArray(arr, size)
{
    var i;
    for (i=0; i < size; i++)
        document.write(arr[i]+ " ");
    document.write("\n");
}

// Driver program 
var arr = [64, 34, 25, 12, 22, 11, 90];
    var n = 7;
    document.write("UnSorted array: \n");
    printArray(arr, n);

    bubbleSort(arr, n);
    document.write("Sorted array: \n");
    printArray(arr, n);


</script>

 

 

Ethix

I'm a coding geek interested in cyberspace who loves to write and read

Leave a Reply

Your email address will not be published.