How to write a program for Insertion Sort & Bubble Sort in Core Java ?

Hello Friends, 

Today I will give you an example for writing a program for Insertion Sort. 

Java Code :

public class ins_sort {
public static void main(String[] args) {
int i;
 int a[] = {40,20,60,30,50,10};
System.out.println(” insertion sorting…..nn”); 
System.out.println(“Before the sort:n”);  
 for(i = 0; i < a.length; i++)
System.out.print( a[i]+”  “);
System.out.println();
 insertion_srt(a, a.length);  
 System.out.print(“Values after the sort:n”);  
 for(i = 0; i
 System.out.print(a[i]+”  “);
System.out.println(); 
 }

 public static void insertion_srt(int a[], int n){
 
 for (int i = 1; i < n; i++){
 
 int j = i;
 
 int B = a[i];
 
 while ((j > 0) && (a[j-1] > B)){
 a[j] = a[j-1];
 j–;
 }
 a[j] = B;
 }
 
}
}

Output :

 insertion sorting…..


Before the sort:

40  20  60  30  50  10  
Values after the sort:

10  20  30  40  50  60  



And this example is  for writing a program for Bubble Sort in java.



Java Code :

public class bubble {
static int a[]={40,50,20,10,30,60};
public static void main(String[] args) {
System.out.println(“Before sorting…”);
display();
bubblesort();
System.out.println(“After sorting…”);
display();
}
public static void bubblesort(){
int temp;
for(int i=0;i
{
for(int j=0;j
{
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
}
public static void display()
{
for(int i=0;i
System.out.println(” “+a[i]);
}
}
}

Output :

Before sorting…
 40
 50
 20
 10
 30
 60
After sorting…
 10
 20
 30
 40
 50
 60

Leave a Reply