Let us understand how Bubble sorting works with diagrammatic representation:
Say for example, if we have array elements as shown below:
65, 47, 70, 9
Pass 1:
To begin with, the element at 0th and 1st index are compared. Their positions are swapped, if element at 0th index is greater than element at 1st index.
Since, 65 is greater than 47, swap occurs.Now, elements at 2nd and 3rd index are compared.
Since, 70 is greater than 9, swap occurs and now, the list will look like this.Below program will teach you how to sort the numbers in an array using Bubble Sorting.
{
public static void main(String[]args)
{
int list[] = {65,47,40,9,37,72,45,17};
int len = list.length;
for(int i = 0;i<len-1;i++)
{
for(int j = 0;j<len-i-1;j++)
{
if(list[j]>list[j+1])
{
//swapping of adjacent elements done here
int tmp = list[j];
list[j] = list[j+1];
list[j+1] = tmp;
}
}
}
System.out.println("Sorted array is");
for(int i = 0;i<len-1;i++)
{
System.out.println(list[i]);
}
}
}
1. A class namely BubbleSort have been defined.
2. A main method have been defined.
3. An array namely list of int data type has been declared and unsorted elements are stored in it.
4. Stores the length of list in len variable.
5. The outer loop iterates through the entire array.
7. Compares two adjacent elements, i.e. element at jth position and that as (j+1)th position.
8. Stores the value of the current element in a temporary variable.
9. Stores the value of the next element of the array in the current element.
10. Stores the value of the temporary variable in the next element