Bubble Sort is an algorithm in which we compare the adjacent elements in a list, and swap them if they are not in proper order. In each iteration, the largest element is placed in its proper position (when sorting in ascending order). The same process is then repeated with the remaining elements. Below is the code written in Java that sorts an array in ascending order, using the bubble sort technique:
class BubbleSort{
public static void main (String args[]){
int a[] = {92, 34, 78, 12, 45, 7, 81, 60, 51, 10};
int i, j, temp;
for (i = 0; i < a.length; i++){
for (j = 0; j < a.length-i-1; j++){
if (a[j] > a[j+1]){
temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
}
for (i = 0; i < a.length; i++)
System.out.print (a[i] + "\t");
System.out.println ();
}
}
Let's see a demonstration of how each iteration takes place in sequence to move the largest element to its proper position. The elements in red denote the adjacent elements which are compared and then swapped (if required):
Since 92 was the largest element, it is finally placed in its proper position while sorting in ascending order. This process is repeated with the remaining elements, until it is assured that the entire list is sorted.
Very Nice Effort. It will really be beneficial for students who are leaning Java. Searching and Sorting is essential if you want to make career in Java.
ReplyDeleteThanks for your feedback Ravi.
ReplyDeleteGood demonstration.Plz u can make demonstration for selection sort.
ReplyDeleteThis comment has been removed by the author.
ReplyDelete