Sort the array elements in Ascending/Descending order using Bubble Sort

Hi guys, Bushan here, welcome back to B2 Tech. Today in this article we will discussing  about one of the most important sorting technique and also an important Java interview program of all time. Given an integer array, sort the array elements in ascending order or descending order using Bubble Sort technique without using sort() method.



Test Case – 1
Input: 5, 2, 1, 8, 9, 4, 6, 0
Output: 0, 1, 2, 4, 5, 6, 8, 9
Test Case – 2
Input: 2, 9, 7, 1, 0, 6, 4, 1
Output: 0, 1, 1, 2, 4, 6, 7, 9



JavaCC++Python
[java] import java.util.Arrays;

public class BubbleSort {
public static void main(String[] args) {
int a[] = {2, 9, 7, 1, 0, 6, 4, 1};
System.out.println(Arrays.toString(bubbleSort(a)));
}
public static int[] bubbleSort(int a[]) {
for(int i = 0; i < a.length – 1; i++) {
for(int j = i+1; j < a.length; j++) { if(a[i] > a[j]) { //for descending change it to ‘<‘
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
return a;
}
}
[/java]



About the author

Bushan Sirgur

Hey guys, I am Bushan Sirgur from Banglore, India. Currently, I am working as an Associate project in an IT company.

View all posts

Leave a Reply

Your email address will not be published. Required fields are marked *