Friday, 11 September 2015

Sorting

Sorting is a process of arranging items in ascending or descending order. This process can be implemented via many different algorithms.
Bubble Sort: This algorithm is based on the idea of repeatedly comparing pairs of  elements and then switching their positions if they exist in the wrong order.
Complexity: The complexity of bubble sort is O(n2) in the worst and average case because for every element we iterate over the the entire array each time.




//Bubble Sort
import java.util.Scanner;
class Bubble
{
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int arr[]=new int[n];
void input()
{
for(int i=0;i<n;i++)
{
System.out.printf("enter the value of %d element:",(i+1));
arr[i]=sc.nextInt();
}
}
void sort()
{
for(int i=0;i<n-1;i++)
{
for(int j=i+1;j<n;j++)
{
if(arr[i]>arr[j])
{
int temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
}
}
}
void display()
{
System.out.println("the sorted array is:");
for(int i=0;i<n;i++)
System.out.print(arr[i]+"\t");
}
void steps()
{
for(int i=0;i<n-1;i++)
{
System.out.printf("Outer Loop i=%d\n",i);
for(int j=i+1;j<n;j++)
{
if(arr[i]>arr[j])
{
int temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
System.out.printf("\t\t Inner Loop j=%d\n",j);
try
{
Thread.sleep(3000);
}
catch(InterruptedException e)
{
System.out.println(e.getMessage());
}
for(int k=0;k<n;k++)
{
System.out.print(arr[k]+"\t");
}
System.out.println();
}
}
}
}
class BubbleTest
{
public static void main(String args[])
{
System.out.println("enter the total number of elements:");
Bubble b1=new Bubble();
b1.input();
//b1.sort();
//b1.display();
b1.steps();
b1.display();
}
}

No comments:

Post a Comment