BUBBLE
SORTING ALGORITHM IN JAVA
Hey guys we are back
with another blog and in this we are going to talk about bubble sorting algo in
java, but before bubble sorting let's get to what sorting actually is. So
sorting is an algorithm in programming languages in which we sort or arrange an
array in ascending order. There are basically three types of sorting algorithm
in java namely, bubble sorting, selection sorting and insertion sorting, but in
this blog obviously we'll discuss the first one.
So consider an array
with numbers 1 to 5 randomly filled in a disorganized way
ar[] = {2,5,1,3,4};
We have to sort this
in an ascending order ( 1,2,3,4,5) , now the bubble sort algorithm compares the
value (at index i) with the value present at (i+1)th index and swaps the two
values if the element at (i+1)th index is smaller than the value at ith index.
So let's understand
it more thoroughly :
Array initially 2 , 5,
1 ,3 ,4
(comparing 0th index
value and 1st index value)
ar[0]<ar[1]
(nothing will happen) 2, 5,
1, 3 , 4
(comparing 1st index
value and 2nd index value)
ar[1]>ar[2] (the
two values will swap with each other) 2 ,1,5 ,3 ,4
(comparing 2nd index
value and 3rd index value)
ar[2]>ar[3] (the
two values will be swapped) 2, 1, 3, 5 ,4
(comparing 3rd index
value and 4th index value)
ar[3]>ar[4] (the two values will swap with each
other) 2, 1, 3, 4, 5
Now the first
iteration is completed but seems that our array isn't completed sorted, so we
will iterate our loop untill the time our array will be fully sorted.
Now for the second
iteration we have:
Array initially
2,
1, 3, 4, 5
(comparing 0th index
value and 1st index value)
ar[0]>ar[1] (the two values will swap with each
other) 1, 2, 3, 4 , 5
(comparing 1st index
value and 2nd index value)
ar[1]<ar[2]
(nothing will happen) 1, 2, 3, 4
, 5
(comparing 2nd index
value and 3rd index value)
ar[2]<ar[3]
(nothing will happen) 1, 2, 3, 4 ,
5
(comparing 3rd index
value and 4th index value)
ar[3]<ar[4]
(nothing will happen) 1, 2, 3, 4 , 5
So now our array is sorted, now we can see that how can we write this algorithm in java
public class Sorting {
public static void main(String[] args) {
int a[] = {2,5,1,3,4};
for (int i=0; i<4;i++) {
for(int j=0; j<4; j++) {
if (a[j+1]<a[j]) {
int temp = a[j+1];
a[j+1]=a[j];
a[j]=temp;
}
}
}
System.out.print("Sorted Array: ");
for(int k=0; k<5; k++) {
System.out.print(a[k]+" ");
}
}
}
Sorted Array: 1 2 3 4 5
No comments:
Post a Comment