Search Bar

Bubble sort in data structure and algorithm!


Java Data Structures and Algorithm:
Bubble sort algorithm.


Hi Developers,

Nowadays everyone (Developer) should know the basics of DSA. Here we will learn about the new DSA algo, a Bubble sort algorithm.

bubble sort algo dsa
Bubble sort DSA



/**

 * What is bubble sort?

 * Bubble sort is one of the sorting algorithms that repeatedly checks whether the element is smaller or   * larger

 * if a[i] is larger and a[i+1] is smaller, then it will swap the numbers, else move to the next element.

 * At the end of the first iteration we got a larger element at the end of the list. And this will repeat for   *  the next

 * iteration till all elements got sorted.

 * 

 * It is like water bubbles, if the bubble is larger, then it will shift right side.

 * 

 * Time Complexity:

 * Bubble sort has a worst-case and average complexity of O(n^2), where n is the number of items         * being sorted

 */


Code:



package com.amolsoftwares;

/**
* Amol Software's
* www.amolsoftwares.com
*/
public class InterviewPrep {

public static void main(String[] args) {

/**
* Q. Using bubble sort find the 3rd largest
* element from an array of integer.
*/

int[] arr = {1, 4, 2, 7, 3, 9, 6, 5};

for (int i=0; i<arr.length-1; i++){
for (int j=0; j<arr.length-i-1; j++){
if (arr[j]>arr[j+1]){
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}

int size = arr.length;

System.out.println("3rd larger number: "+ arr[size-3]);
/**
* By default, it sort in ascending order.
* if we want it in descending order can can change the condition
*
*/
}

}

/**
* What is bubble sort?
* Bubble sort is one of the sorting algorithm that
* repeatedly check the element is smaller or larger
* if a[i] is larger and a[i+1] is smaller, then it will
* swap the numbers, else move to next element.
* At the end of first iteration we got larger element at
* end of the list. And this will repeat for next
* iteration till all element got sorted.
* <p>
* It is like water bubbles, if the bubble is larger, then
* it will shift right side.
* <p>
* Time Complexity:
* Bubble sort has a worst-case and average complexity
* of O(n^2), where n is the number of items being sorted
*/



Post a Comment

0 Comments