public class bubbleSort{
public static void main(String a[]){
int i;
int array[] = {12,9,4,99,120,1,3,10};
System.out.println("Values Before the sort:\n");
for(i = 0; i < array.length; i++)
System.out.print( array[i]+" ");
System.out.println();
bubble_srt(array, array.length);
System.out.print("Values after the sort:\n");
for(i = 0; i <array.length; i++)
System.out.print(array[i]+" ");
System.out.println();
System.out.println("PAUSE");
}
public static void bubble_srt( int a[], int n ){
int i, j,t=0;
for(i = 0; i < n; i++){
for(j = 1; j < (n-i); j++){
if(a[j-1] > a[j]){
t = a[j-1];
a[j-1]=a[j];
a[j]=t;
}
}
}
}
}Bubble Sort in Different Languages
In Bubble Sort there is a loop within a loop. Hence, we can say that the Best Case and the Worst Case is O(n^2)
Java
C++
# ifndef __BUBBLESORT_HEADER__
# define __BUBBLESORT_HEADER__
# include <something>
template <class itemType, class indexType=int>
void BubbleSort(itemType a[], indexType l, indexType r)
{
static indexType i, j;
for(i=r; i>l; --i)
for(j=l; j<i; ++j)
if(a[j] > a[j+1]) std::swap(a[j], a[j+1]);
}
# endif
Pascal Language
Procedure BubbleSort(numbers : Array of Integer; size : Integer); Var i, j, temp : Integer; Begin
For i := size-1 DownTo 1 do
For j := 2 to i do
If (numbers[j-1] > numbers[j]) then
Begin
temp := numbers[j-1];
numbers[j-1] := numbers[j];
numbers[j] := temp;
End;
End.
Language Implementation:
Pascal Language
C Language
for(int x=0; x<n; x++)
{
for(int y=0; y<n-1; y++)
{
if(array[y]>array[y+1])
{
int temp = array[y+1];
array[y+1] = array[y];
array[y] = temp;
}
}
}
Language Implementation:
C Language
Subscribe to:
Comments (Atom)