Sorting
1. Write a Program for Bubble Sort.
import java.io.*;
public class BubbleSort{
public static void main(String args[])throws Exception
{
BufferedReader br1=new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter the Size of the Array: ");
int size=Integer.parseInt(br1.readLine());
int arr[]=new int[size];
for(int a=0;a
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter The "+(a+1)+" Element=");
arr[a]=Integer.parseInt(br.readLine());
}
for(int i=0; i<arr.length;i++)
{
for(int k=1; k<arr.length;k++)
{
if(arr[k-1]>arr[k])
{
int j=arr[k-1];
arr[k-1]=arr[k];
arr[k]=j;
}
}
}
System.out.print("Sorted Elements are: ");
for(int b=0;b
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.print(" "+arr[b]);
}
}
}
Bubble sort Example: 6, 5, 1, 7, 2, 4, 9
Array size=7
5,6,1,7,2,4,9
5,1,6,7,2,4,9
5,1,6,7,2,4,9
5,1,6,2,7,4,9
5,1,6,2,4,7,9
5,1,6,2,4,7,9
=============
1,5,6,2,4,7,9
1,5,2,6,4,7,9
1,5,2,4,6,7,9
=============
1,2,5,4,6,7,9
1,2,4,5,6,7,9
=============
2. Write a Program for Selection Sort.
public void SelectionSort()
Array size=7
5,6,1,7,2,4,9
5,1,6,7,2,4,9
5,1,6,7,2,4,9
5,1,6,2,7,4,9
5,1,6,2,4,7,9
5,1,6,2,4,7,9
=============
1,5,6,2,4,7,9
1,5,2,6,4,7,9
1,5,2,4,6,7,9
=============
1,2,5,4,6,7,9
1,2,4,5,6,7,9
=============
2. Write a Program for Selection Sort.
{
for (int b=arr.length-1;b>0;b--)
{
int maxPosition=0;
for(int c=1;c<=b;c++)
{
if(arr[c]>arr[maxPosition])
maxPosition=c;
}
int l=arr[maxPosition];
arr[maxPosition]=arr[b];
arr[b]=l;
}
}
Selection sort Example:
4, 3, 5, 6, 1
Maxposition=2
4, 3, 5, 6, 1
Maxposition=3
4, 3, 5, 6, 1
=============
4, 3, 5, 1, 6
4, 3, 5, 1, 6
=============
4, 3, 1, 5, 6
=============
1, 3, 4, 5, 6
3. Write a Program for Insertion Sort.
3. Write a Program for Insertion Sort.
public void InsertionSort()
{
long timeNs=System.nanoTime();
for(int i=1;i<arr.length;i++)
{
int current=arr[i];
int j=i;
while(j>0 && arr[j-1]>current)
{
arr[j]=arr[j-1];
j--;
}
arr[j]=current;
}
nanoTime=System.nanoTime()-timeNs;
}
No comments:
Post a Comment