Bubble Sorting in Java
Introduction
In
this example we are going to sort integer values of an array using bubble
sort.
Bubble sort is also known as exchange sort. Bubble sort is a simplest sorting algorithm. In bubble sort algorithm array is traversed from 0 to the length-1 index of the array and compared one element to the next element and swap values in between if the next element is less than the previous element. In other words, bubble sorting algorithm compare two values and put the largest value at largest index. The algorithm follow the same steps repeatedly until the values of array is sorted. In worst-case the complexity of bubble sort is O(n2) and in best-case the complexity of bubble sort is Ω(n).
Bubble sort is also known as exchange sort. Bubble sort is a simplest sorting algorithm. In bubble sort algorithm array is traversed from 0 to the length-1 index of the array and compared one element to the next element and swap values in between if the next element is less than the previous element. In other words, bubble sorting algorithm compare two values and put the largest value at largest index. The algorithm follow the same steps repeatedly until the values of array is sorted. In worst-case the complexity of bubble sort is O(n2) and in best-case the complexity of bubble sort is Ω(n).
Here are code
class BubbleSorting{
public static void main(String arg[]){
int a[]={2,33,54,12,0,46,34,22,4,4,4,4};
System.out.println("\n\nInput values:");
for(int i=0;i<a.length;i++){
System.out.print(" "+a[i]);
}
for (int i = a.length; --i>=0; ){
for (int j = 0; j<i; j++){
if (a[j] > a[j+1])
{
int T = a[j];
a[j] = a[j+1];
a[j+1] = T;
}
}
}
System.out.println("\n\n\nSorted values:");
for(int i=0;i<a.length;i++)
{
System.out.print(" "+a[i]);
}
}
}
No comments:
Post a Comment