Search Java Programs

Tuesday, January 19, 2010

Prime Number in Java

Here is the code of the Program
import java.io.*;

class PrimeNumber {
public static void main(String[] args) throws Exception{
int i;
BufferedReader bf = new BufferedReader(
new InputStreamReader(System.in));
System.out.println("Enter number:");
int num = Integer.parseInt(bf.readLine());
System.out.println("Prime number: ");
for (i=1; i < num; i++ ){
int j;
for (j=2; j<i; j++){
int n = i%j;
if (n==0){
break;
}
}
if(i == j){
System.out.print(" "+i);
}
}
}
}

Find out the prime number

Here is the code program:
class Prime_number {
public static void main(String[] args) {
int num = 11;
int i;
for (i=2; i < num ;i++ ){
int n = num%i;
if (n==0){
System.out.println("not Prime!");
break;
}
}
if(i == num){
System.out.println("Prime number!");
}
}
}

Preparing table of a number by using loop

Here is the code of the prorgram:
class  PreparingTable{
public static void main(String[] args) {
int a=25, b=1;
System.out.println("the table of "+a+"= ");
while(b<=10){
int c = a*b;
System.out.println(c);
b = b+1;
}
}
}

Listing out leap years between certain period

Here is the code of the program:
class leapyears
{
public static void main(String[] args)
{
int i=2006;
int n;
for (n=1990; n<=i ; n++){
int l=n%4;
if (l==0){
System.out.println("leap year: "+n);
}
}
}
}
Download this program.

Checking whether a year is leap or not

Here is the code of program:
class  Leapyear
{
public static void main(String[] args)
{
int n=2000;
if (n%4==0){
System.out.println("The given year is a leap year");
}
else{
System.out.println("This is not a leap year");
}
}
}
Download the program:

Write a program to construct a triangle with the ?*?

Here is the code of the program:
import java.io.*;

class triangle{
public static void main(String[] args) {
try{
BufferedReader object = new BufferedReader(new InputStreamReader(System.in));
System.out.println("enter the number");
int a= Integer.parseInt(object.readLine());
for (int i=1; i<a;i++ ){
for (int j=1; j<=i;j++ ){
System.out.print("*");
}
System.out.println("");
}
}
catch(Exception e){}
}
}
Download the program.

Write a program for calculating area and perimeter of a rectangle

Here is the code of the program:
import java.io.*;
class RecArea
{
public static void main(String[] args)
{

int l=0;
int w=0;

try{

BufferedReader br1 = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter length of rectangle : ");
l = Integer.parseInt(br1.readLine());
System.out.println("Enter width of rectangle : ");
w = Integer.parseInt(br1.readLine());
int area = l*w;
System.out.println("Area of Rectangle : "+area);
int perimiter = 2*(l+w);
System.out.println("Perimeter: " + perimiter);

}catch(Exception e){System.out.println("Error : "+e);}

}
}
Download this example.

Palindrome Number Example in Java

Description of program:

With the help of this program, we are going to determine whether the given number is palindrome or not. To achieve the desired result, firstly we have to define a class named "Palindrome". After that we will ask the user to enter any integer type number and then we will reverse it. After reversing the number we will check whether the given number is palindrome or not. If the given number is larger, then it will display a message "Out of range!".

Here is the code of this program

import java.io.*;

public class Palindrome {
public static void main(String [] args){
try{
BufferedReader object = new BufferedReader(
new InputStreamReader(System.in));
System.out.println("Enter number");
int num= Integer.parseInt(object.readLine());
int n = num;
int rev=0;
System.out.println("Number: ");
System.out.println(" "+ num);
for (int i=0; i<=num; i++){
int r=num%10;
num=num/10;
rev=rev*10+r;
i=0;
}
System.out.println("After reversing the number: "+ " ");
System.out.println(" "+ rev);
if(n == rev){
System.out.print("Number is palindrome!");
}
else{
System.out.println("Number is not palindrome!");
}
}
catch(Exception e){
System.out.println("Out of range!");
}
}
}
Download this example

calculate factorial of any given number

Here is the code of the program:
import java.io.*;
class Factorial{
public static void main(String[] args) {
try{
BufferedReader object = new BufferedReader(new InputStreamReader(System.in));
System.out.println("enter the number");
int a= Integer.parseInt(object.readLine());
int fact= 1;
System.out.println("Factorial of " +a+ ":");
for (int i= 1; i<=a; i++){
fact=fact*i;
}
System.out.println(fact);
}
catch (Exception e){}
}
}

Download this example.

Updated Example description

This is the updated example of factorial that will evaluates the factorial of number in double which is lies in the range of double data type in java.

Here is the code of program:

import java.io.*;

class Factorial1{
public static void main(String[] args) {
try{
BufferedReader object = new BufferedReader(
new InputStreamReader(System.in));
System.out.println("enter the number");
int a= Integer.parseInt(object.readLine());
double fact= 1;
System.out.println("Factorial of " +a+ ":");
for (int i= 1; i<=a; i++){
fact=fact*i;
}
System.out.println(fact);
}
catch (Exception e){
System.out.println("Array out of bounds exaception");
}
}
}
Download this example.

Write a program to calculate area and perimeter of a circle

Here is the code of the program:
import java.io.*;
class CircleArea{
public static void main(String[] args){
int r=0;
try{
BufferedReader br1 = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter Radius of Circle : ");
r = Integer.parseInt(br1.readLine());
double area = java.lang.Math.PI*r*r;
System.out.println("Area of Circle : "+area);
double perimeter =2*java.lang.Math.PI*r ;
System.out.println("Perimeter of Circle : "+perimeter);
}
catch(Exception e){
System.out.println("Error : "+e);
}
}
}
Download this example.

Math class in Java

In this example you will learn about Math class. This example explains how you can use functions provided by the Math class like E, PI, round, abs, ceil, exp, floor, IEEEremainder, max, min, pow, random, rint, sqrt etc. to manipulate the mathematical operation in your program. The Math class is used to operate the calculations. There is not necessary to import any package for the Math class because this is already in java.lang package.

Any expressions can be operated through certain method calls. There are some functions have been used in the given example. All the functions have been explained below with example :

E

This is E field of the Math class which returns you a default exponent value that is closer than any other to e, the base of the natural logarithms.

PI

This is also a field of the Method class which returns you a default pi value, the ratio of the circumference of a circle to its diameter.

abs()

This is the abs() function which returns you the absolute number.

ceil()

This is the ceil() function which returns you the smallest value but greater than the argument.

exp()

This is the exp() function which returns you the exponential value raised to the power of a double value.

floor()

This is the floor() function which returns you the largest value but less than the argument.

IEEEremainder()

This is the IEEEremainder() which returns you the remainder for the given dividend and divisor.

max()

This is the max() function which distinguishes the maximum value from the two given value.

min()

This is the min() function which distinguishes the minimum value from the two given value.

pow()

This is the pow() function which returns you the number raised to the power of a first given value by the another one.

random()

This is the random() function which returns you the random number. It is absolutely system generated.

rint()

This is the rint() function which returns you a value closest to the given value.

round()

This is the round() function which returns you a value that is in the rounded form.

sqrt()

This is the sqrt() function which returns you the square root of the specified value.

Code for the program :

 public class mathclass{
public static void main(String[] args){
//E and round()
System.out.println("e = " + Math.round(Math.E*100)/100f);
//PI
System.out.println("pi = " + Math.round(Math.PI*100)/100f);
//abs()
System.out.println("Absolute number = " + Math.abs(Math.PI));
//ceil()
System.out.println("Smallest value but greater than

the argument = " + Math.ceil(Math.PI));
//exp()
System.out.println("Exponent number powered by

the argument = " + Math.exp(0));
//floor()
System.out.println("Largest value but less

than the argument = " + Math.floor(Math.E));
//IEEEremainder()
System.out.println("Remainder = " +

Math.IEEEremainder(5.3f,2.2f));
//max()
System.out.println("Maximum Number = " +

Math.max(10,10.3));
//min()
System.out.println("Minimum Number = " +

Math.min(10,10.3));
//pow()
System.out.println("Power = " + Math.pow(10,3));
//random()
System.out.println("Random Number = " +

Math.random());
//rint()
System.out.println("Closest to the Argument

= " + Math.rint(30));
//round()
System.out.println("Round = " + Math.round(Math.E));
//sqrt()
System.out.println("Square Root = " + Math.sqrt(400));
}
}
Download Math Class Example

Write a program to list all even numbers between two numbers

import java.io.*;

class AllEvenNum{
public static void main(String[] args) {
try{
BufferedReader br1 = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter number : ");
int num = Integer.parseInt(br1.readLine());
System.out.println("Even Numbers:");
for (int i=1;i <=num ; i++){
if(i%2==0 ){
System.out.print(i+",");
}
}
}
catch(Exception e){}

}
}

Determining the largest number

class largernumber{
public static void main(String[] args) {
int x=500, y=70, z=3000;
if (x>y){
if (x>z){
System.out.println("x is greater");
}
else{
if(z>y){
System.out.println("z is greater");
}
else{
System.out.println("y is greater");
}
}
}
else{
if (y>z){
System.out.println("y is greater");
}
}
}
}

Calendar Example

In this section, we are discussing the entire functionality of java.util.Calender class. In the following code segment we are performing various operations on Date object using its methods. The method getTime() of the calendar class returns a Date object that is then passed to the println() method just to print today's date. The arithmetic function of the date class adds specific amount of time to the given time field following the calendar's rule. This example subtracts two years from the current date of the calendar and also add 3 days to the current date of the calendar.

Description of program:

In the following code segment, first we are getting the current date and time into the date object by using the
getInstance() and getTime() methods of the calendar class in a method CalendarTimemethod() and printing this current date and time on the console.

Then we are taking another method SimpleDateFormatmethod(), this method is getting an instance of the calendar class into the date object. Now we are taking an object of SimpleDateFormat class. Now we are getting the current date and time from the date object by calling getTime() method on this object. Now we are passing this current date and time into the format() method of the dateformatter object (SimpleDateFormat class) just to get the current date and time into the simple date format, after that we are printing current date and time on the console.

Now we are taking another method Adddates() that adds two different dates. In this method we are taking an instance date of the calendar class into a reference variable cldr and an object dateformatter of the SimpleDateFormat class. Now we are taking the clone of the calendar class and passing the reference of this clone into cldr. Now we are getting the dates of two years ago and five years after, by using the add() method and printing these values on the console.

Now we are taking another method that is DateDifference(). In this method we are taking date and time from an object of the GregorianCalendar class and passing it into an object startDate1 of the Date class and also taking an another object endDate1 of the date class. Now we are taking the difference of times of these two objects and printing it on the console.

Now in the last Getcalendermethods() we are displaying values to demonstrate the various method of the calendar class.

Here is the code of program:


  import java.util.Date;
import java.util.Calendar;
import java.text.SimpleDateFormat;
import java.util.*;

public class CalendarExample {

private static void CalendarTimemethod() {
Date date = Calendar.getInstance().getTime();
System.out.println("Current date and time is: " + date);
System.out.println();
}

private static void SimpleDateFormatmethod() {
Calendar date = Calendar.getInstance();
SimpleDateFormat dateformatter = new SimpleDateFormat
("E yyyy.MM.dd 'at' hh:mm:ss a zzz");
System.out.println("Current date and

time in simple date format: "
+ dateformatter.format(date.getTime()));
System.out.println();
}

private static void Adddates() {

System.out.println("Performing

operations on calendar dates.");

// Get today's date
Calendar date = Calendar.getInstance();
Calendar cldr;
SimpleDateFormat dateformatter = new SimpleDateFormat
("E yyyy.MM.dd 'at' hh:mm:ss a zzz");

cldr = (Calendar) date.clone();
cldr.add(Calendar.DAY_OF_YEAR, - (365 * 2));
System.out.println("Before two years it was: "
+ dateformatter.format(cldr.getTime()));

cldr = (Calendar) date.clone();
cldr.add(Calendar.DAY_OF_YEAR, + 5);
System.out.println("After five years it will be: "
+ dateformatter.format(cldr.getTime()));

System.out.println();
}

private static void DateDifference() {

System.out.println("Difference between two dates");
Date startDate1 = new GregorianCalendar(2005, 02,

25, 14, 00).getTime();
Date endDate1 = new Date();;

long diff = endDate1.getTime() - startDate1.getTime();

System.out.println(" Difference between " + endDate1);
System.out.println(" and " + startDate1 + " is "
+ (diff /

(1000L*60L*60L*24L)) + " days.");
System.out.println();
}

private static void Getcalendermethods() {

System.out.println("Various get methods

of the calendar class:");
Calendar calender = Calendar.getInstance();

System.out.println("Year : "

+ calender.get(Calendar.YEAR));
System.out.println("Month : "

+ calender.get(Calendar.MONTH));
System.out.println("Day of Month : "

+ calender.get(Calendar.DAY_OF_MONTH));
System.out.println("Day of Week : "

+ calender.get(Calendar.DAY_OF_WEEK));
System.out.println("Day of Year : "

+ calender.get(Calendar.DAY_OF_YEAR));
System.out.println("Week of Year : "

+ calender.get(Calendar.WEEK_OF_YEAR));
System.out.println("Week of Month : "

+ calender.get(Calendar.WEEK_OF_MONTH));
System.out.println
("Day of the Week in Month : "

+ calender.get(Calendar.DAY_OF_WEEK_IN_MONTH));
System.out.println("Hour

: " + calender.get(Calendar.HOUR));
System.out.println("AM PM

: " + calender.get(Calendar.AM_PM));
System.out.println("Hour of the Day

: " + calender.get(Calendar.HOUR_OF_DAY));
System.out.println("Minute

: " + calender.get(Calendar.MINUTE));
System.out.println("Second

: " + calender.get(Calendar.SECOND));
System.out.println();
}

public static void main(String[] args) {
System.out.println();
CalendarTimemethod();
SimpleDateFormatmethod();
Adddates();
DateDifference();
Getcalendermethods();
}
}

Here is the output:

C:\Examples>java CalendarExample

Current date and time is: Mon Dec 10 18:37:06 GMT+05:30 2007

Current date and time in simple date format: Mon 2007.12.10 at 06:37:07 PM GMT+05:30

Performing operations on calendar dates.
Before two years it was: Sat 2005.12.10 at 06:37:07 PM GMT+05:30
After five years it will be: Sat 2007.12.15 at 06:37:07 PM GMT+05:30

Difference between two dates
Difference between Mon Dec 10 18:37:07 GMT+05:30 2007
and Fri Mar 25 14:00:00 GMT+05:30 2005 is 990 days.

Various get methods of the calendar class:
Year : 2007
Month : 11
Day of Month : 10
Day of Week : 2
Day of Year : 344
Week of Year : 50
Week of Month : 3
Day of the Week in Month : 2
Hour : 6
AM PM : 1
Hour of the Day : 18
Minute : 37

Download of this program.

Heap Sort in Java

Introduction

In this example we are going to sort integer values of an array using heap sort.

There are two types of heap. First one is Max heap and second one is min heap. Max heap is a special type of binary tree .The roots of the max heap is greater than its child roots. Other heap is min heap it is also a special type of heap which has minimum root than his child. We can sort the array values using heap sorting algorithm. In this algorithm the heap build is used to rebuild the heap.
In this example we sorting all elements of an array. The complexity of the heap sort is O(n.log(n)). Heap sort is slowest but it is better option for large data sets.

The example of Max heap:


Code description:
To sort a heap Build Heap algorithm is used to build a heap out of the data set .Then remove the root element and replace the last element at the position of root node. Then rearrange the heap. Place the root node in an array. Follow these steps until all elements in heap is not replace into array. The values in array will be in sorted order.

Steps of heap sort algorithm:
1. Remove the parent root and replace it with the rightmost leaf.
2.Strore parent root in an array.
3. Re-establish the heap.
4. Repeat steps 1 and 3 until values in heap is not zero.

Working of heap sort
algorithm:
Input:1,3,5,4,2
Step1:
Buid Heap tree and an array of same size.




Step2:
Remove largest root and add largest root in array.

Step3:
Replace last value (eg 2) at at root node position.

Step4:
Swap 2 and 4

Step5:
Swap 2 and 3.


Step6:
Remove 4 and replace 2 at position of 4 and add 4 in array


Step7:
Swap 2 and 3


Step8:
Remove 3 ,add in array and replace 1 at position of 3.


Step9:
Swap 2 and 1.

Step10:
Remove 2 and it at root position



Step11:
Remove 1 and add in array.


Output:
Sorted array 1,2,3,4,5

The code of the program :

public class heap_Sort{
public static void main(String a[]){
int i;
int arr[] = {1,3,4,5,2};

System.out.println("\n Heap Sort\n---------------\n");
System.out.println("\n Unsorted Array\n\n");
for (i = 0; i < arr.length; i++)
System.out.print(" "+arr[i]);
for(i=arr.length; i>1; i--){
fnSortHeap(arr, i - 1);
}
System.out.println("\n Sorted array\n---------------\n");
for (i = 0; i < arr.length; i++)
System.out.print(" "+arr[i]);
}

public static void fnSortHeap(int array[], int arr_ubound){
int i, o;
int lChild, rChild, mChild, root, temp;
root = (arr_ubound-1)/2;

for(o = root; o >= 0; o--){
for(i=root;i>=0;i--){
lChild = (2*i)+1;
rChild = (2*i)+2;
if((lChild <= arr_ubound) && (rChild <= arr_ubound)){
if(array[rChild] >= array[lChild])
mChild = rChild;
else
mChild = lChild;
}
else{
if(rChild > arr_ubound)
mChild = lChild;
else
mChild = rChild;
}

if(array[i] < array[mChild]){
temp = array[i];
array[i] = array[mChild];
array[mChild] = temp;
}
}
}
temp = array[0];
array[0] = array[arr_ubound];
array[arr_ubound] = temp;
return;
}
}

Output of the example:

C:\array\sorting>Javac heap_Sort.java
C:\array\sorting>java heap_Sort
  Heap Sort
---------------
  Unsorted Array
 1 3 4 5 2
Sorted array
---------------
 1 2 3 4 5

Copying Arrays - arraycopy()

After learning all about arrays, there is still one interesting thing left to learn i.e. copying arrays. It means to copy data from one array to another. The precise way to copy data from one array to another is
public static void arraycopy(Object source,
int srcIndex,
Object dest,
int destIndex,
int length)
Thus apply system's arraycopy method for copying arrays.The parameters being used are :-
src the source array
srcIndex start position (first cell to copy) in the source array
dest the destination array
destIndex start position in the destination array
length the number of array elements to be copied

The following program, ArrayCopyDemo(in a .java source file), uses arraycopy to copy some elements from the copyFrom array to the copyTo array.

public class ArrayCopyDemo{
public static void main(String[] args){
char[] copyFrom = {'a','b','c','d','e','f','g','h','i','j'};
char[] copyTo = new char[5];
System.arraycopy(copyFrom, 2, copyTo, 0, 5);
System.out.println(new String (copyTo));
}
}

Output of the program:

C:\tamana>javac ArrayCopyDemo.java
C:\tamana>java ArrayCopyDemo
cdefg
C:\tamana>

In this example the array method call begins the copy of elements from element number 2. Thus the copy begins at the array element 'c'. Now, the arraycopy method takes the copied element and puts it into the destination array. The destination array begins at the first element (element 0) which is the destination array copyTo. The copyTo copies 5 elements : 'c', 'd', 'e', 'f', 'g'. This method will take "cdefg" out of "abcdefghij", like this :

Following image illustrates the procedure of copying array from one to another.

Donwload this example.

Comparing Two Numbers

class  Comparing{
public static void main(String[] args) {
int a=24, b=25;
if (a == b){
System.out.println("Both are equal");
}
else if(a>b){
System.out.println("a is greater than b");
}
else{
System.out.println("b is greater than a");
}
}
}

Beginners Java Tutorials - Installing JDK

In this beginners java Tutorial ,We will first download, install and configure the J2SE development environment.

Downloading and Installing J2SE Software on Windows Platform
To download J2SE for development visit http://www.java.sun.com/j2se and download J2SE on your machine. In this tutorial we have used jdk-1_5_0_06-windows-i586.exe.The java 2Platform or (JDK) can be downloaded from the sun. Formerly Known as the java Development kit ,or JDK, Downloading java is really about downloading the java 2 plat form that comes in three editions , J2ME, J2SE and J2EE , if you are learning java, then, you should start by downloading J2EE.

Once you have downloaded the j2se on your system, you are ready to install . In the following section we will learn how to install jdk development environment on your machine. here are the step to install JDK on your windows machine.

Step 1

Double click the JDK down loaded file, the executable extracts the required Contents to the temporary directory and then License agreement screen appears. On the license agreement page read and accept the license and the click the next button .

Step 2

The custom setup screen appears as follows.

Step 3

Click on the change button to change the installation directory to "c:\jdk1.5.0_06" as shown in the following screen.

and click on the "OK" button. After clicking on the "OK" button installation begins:

Step 4

In the next window installer asks for the installing the runtime as shown in the following screen:

Step 5

Click on next button install the J2SE runtime on your machine. Next screen shows the browser selection:

Click on the "Next" button.

Step 6

Once the installation is finished it shows you the final screen indications the success. Now you have successfully installed J2SE on your machine. Installer shows the following final confirmation window as shown below:

Click on the "Finish" button to exit from the installer.

Configuring the installation on windows machine:

In this Section we will add some settings to the windows environment so that the java compiler and runtime becomes available for compiling and running the java application.

Go to the control panel and double click on "System Properties" and to to the advance tab.

and add "c:\jdk1.5.0_06" to path variable:

and click on ok button. To save the setting click on "OK" button.

This will make the java environment available for development. Open the dos prompt and type javac on the console, it should show the following output:


Microsoft Windows 2000 [Version 5.00.2195]
(C) Copyright 1985-2000 Microsoft Corp.

C:\Documents and Settings\Administrator>java
Usage: java [-options] class [args...]
(to execute a class)
or java [-options] -jar jarfile [args...]
(to execute a jar file)

where options include:
-client to select the "client" VM
-server to select the "server" VM
-hotspot is a synonym for the "client" VM [deprecated]
The default VM is client.

-cp
-classpath
A ; separated list of directories, JAR archives,
and ZIP archives to search for class files.
-D=
set a system property
-verbose[:class|gc|jni]
enable verbose output
-version print product version and exit
-version:
require the specified version to run
-showversion print product version and continue
-jre-restrict-search | -jre-no-restrict-search
include/exclude user private JREs in the version search
-? -help print this help message
-X print help on non-standard options
-ea[:...|:]
-enableassertions[:...|:]
enable assertions
-da[:...|:]
-disableassertions[:...|:]
disable assertions
-esa | -enablesystemassertions
enable system assertions
-dsa | -disablesystemassertions
disable system assertions
-agentlib:[=]
load native agent library , e.g. -agentlib:hprof
see also, -agentlib:jdwp=help and -agentlib:hprof=help
-agentpath:[=]
load native agent library by full pathname
-javaagent:[=]
load Java programming language agent, see java.lang.instrument


C:\Documents and Settings\Administrator>

Now your development environment is ready for development.

Selection Sort In Java

Introduction

In this example we are going to sort the values of an array using selection sort.

In selection sorting algorithm, find the minimum value in the array then swap it first position. In next step leave the first value and find the minimum value within remaining values. Then swap it with the value of minimum index position. Sort the remaining values by using same steps. Selection sort is probably the most intuitive sorting algorithm to invent.

The complexity of selection sort algorithm is in worst-case, average-case, and best-case run-time of Θ(n2), assuming that comparisons can be done in constant time.

Code description:

In selection sort algorithm to find the minimum value in the array. First assign minimum index in key (index_of_min=x). Then find the minimum value and assign the index of minimum value in key (index_of_min=y). Then swap the minimum value with the value of minimum index.
At next iteration leave the value of minimum index position and sort the remaining values by following same steps.

Working of the selection sort :

Say we have an array unsorted A[0],A[1],A[2]................ A[n-1] and A[n] as input. Then the following steps are followed by selection sort algorithm to sort the values of an array . (Say we have a key index_of_min that indicate the position of minimum value)
1.Initaily varaible index_of_min=0;
2.Find the minimum value in the unsorted array.
3.Assign the index of the minimum value into index_of_min variable.
4.Swap minimum value to first position.
5.Sort the remaining values of array (excluding the first value).

The code of the program :

public class selectionSort{
public static void main(String a[]){
int i;
int array[] = {12,9,4,99,120,1,3,10};
System.out.println("\n\n RoseIndia\n\n");
System.out.println(" Selection Sort\n\n");
System.out.println("Values Before the sort:\n");
for(i = 0; i < array.length; i++)
System.out.print( array[i]+" ");
System.out.println();
selection_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 selection_srt(int array[], int n){
for(int x=0; x<n; x++){
int index_of_min = x;
for(int y=x; y<n; y++){
if(array[index_of_min]<array[y]){
index_of_min = y;
}
}
int temp = array[x];
array[x] = array[index_of_min];
array[index_of_min] = temp;
}
}
}

Output of the example:

C:\array\sorting>javac selectionSort.java
C:\array\sorting>java selectionSort
       RoseIndia
       Selection Sort
Values Before the sort:
12 9 4 99 120 1 3 10

Values after the sort:
120 99 12 10 9 4 3 1

Quick Sort In Java

Introduction

In this example we are going to sort integer values of an array using quick sort.

Quick sort algorithm is developed by C. A. R. Hoare. Quick sort is a comparison sort. The working of quick sort algorithm is depending on a divide-and-conquer strategy. A divide and conquer strategy is dividing an array into two sub-arrays. Quick sort is one of the fastest and simplest sorting algorithm. The complexity of quick sort in the average case is Θ(n log(n)) and in the worst case is Θ(n2).

Code description:

In quick sort algorithm pick an element from array of elements. This element is called the pivot. Then compare the the values from left to right until a greater element is find then swap the values. Again start comparison from right with pivot. When lesser element is find then swap the values. Follow the same steps until all elements which are less than the pivot come before the pivot and all elements greater than the pivot come after it. After this partitioning, the pivot is in its last position. This is called the partition operation. Recursively sort the sub-array of lesser elements and the sub-array of greater elements.

Working of quick sort
algorithm:
Input:
12 9 4 99 120 1 3 10 13




Output:
1 3 4 10 12 13 99 120

The code of the program :

public class QuickSort{
public static void main(String a[]){
int i;
int array[] = {12,9,4,99,120,1,3,10,13};

System.out.println("\n\n RoseIndia\n\n");
System.out.println(" Quick Sort\n\n");
System.out.println("Values Before the sort:\n");
for(i = 0; i < array.length; i++)
System.out.print( array[i]+" ");
System.out.println();
quick_srt(array,0,array.length-1);
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 quick_srt(int array[],int low, int n){
int lo = low;
int hi = n;
if (lo >= n) {
return;
}
int mid = array[(lo + hi) / 2];
while (lo < hi) {
while (lo<hi && array[lo] < mid) {
lo++;
}
while (lo<hi && array[hi] > mid) {
hi--;
}
if (lo < hi) {
int T = array[lo];
array[lo] = array[hi];
array[hi] = T;
}
}
if (hi < lo) {
int T = hi;
hi = lo;
lo = T;
}
quick_srt(array, low, lo);
quick_srt(array, lo == low ? lo+1 : lo, n);
}
}

Output of the example:

C:\array\sorting>javac QuickSort.java
C:\array\sorting>java QuickSort
       RoseIndia
       Quick Sort
Values Before the sort:
12 9 4 99 120 1 3 10 13

Values after the sort:
1 3 4 9 10 12 13 99 120

Multi-dimensional arrays

So far we have studied about the one-dimensional and two-dimensional arrays. To store data in more dimensions a multi-dimensional array is used. A multi-dimensional array of dimension n is a collection of items. These ite

ms are accessed via n subscript expressions. For example, in a language that supports it, the element of the two-dimensional array x is denoted by x[i,j].
The Java programming language does not really support multi-dimensional arrays. It does, however, supports an array of arrays. In Java, a two-dimensional array 'x' is an array of one-dimensional array. For instance :-

int[][] x = new int[3][5];

The expression x[i] is used to select the one-dimensional array; the expression x[i][j] is ued to select the element from that array. The first element of this array will be indexed with the "0" value and the last integer will be referenced by "length-1" indexed value. There is no array assignment operator.

Odd Even Transposition Sort In Java

Introduction

In this example we are going to sort integer values of an array using odd even transposition sort.

Odd even transposition sort is a parallel sorting algorithm. Odd Even is based on the Bubble Sort technique of comparing two numbers and swapping them and put higher value at larger index .In each parallel computational steps can pair off either the odd or even neighboring pairs. Each number (In Processing Element-PE) would look to it's right neighbor and if it were greater, it would swap them.

Code description:
The odd even transposition sort is a parallel sorting algorithm. That mean more than one compression can made at one iteration. The comparison is same as bubble sort.

Working of odd even transposition sort:


The code of the program :

public class OddEvenTranspositionSort{
public static void main(String a[]){
int i;
int array[] = {12,9,4,99,120,1,3,10,13};

System.out.println("\n\n RoseIndia\n\n");
System.out.println(" Odd Even Transposition Sort\n\n");
System.out.println("Values Before the sort:\n");
for(i = 0; i < array.length; i++)
System.out.print( array[i]+" ");
System.out.println();
odd_even_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 odd_even_srt(int array[],int n){
for (int i = 0; i < n/2; i++ ) {
for (int j = 0; j+1 < n; j += 2)
if (array[j] > array[j+1]) {
int T = array[j];
array[j] = array[j+1];
array[j+1] = T;
}
for (int j = 1; j+1 < array.length; j += 2)
if (array[j] > array[j+1]) {
int T = array[j];
array[j] = array[j+1];
array[j+1] = T;
}
}
}
}

Output of the example:

C:\array\sorting>javac OddEvenTranspositionSort.java
C:\array\sorting>java OddEvenTranspositionSort
       RoseIndia
       Odd Even Transposition Sort
Values Before the sort:
12  9  4  99  120  1  3  10  13
Values after the sort:
1 3 4 9 10 12 13 99 120

Extra Storage Merge Sort in Java

Introduction

In this example we are going to sort integer values of an array using extra storage merge sort.

In extra storage merge sorting algorithm the unsorted values divide into two equal parts iteratively and create an array for store data value in extra storage. Then merge the two parts , sort it and store into an array .Then again merge the next part , sort it and store into an array. Do it iteratively
until the values are not in sorted order. In this sorting the number of elements must be even.

Code description:
In
extra storage is similar to merge sort .But in extra storage merge sort the sorted values are stored in an other array.

Working of
extra storage merge sort algorithm:

Say we have an array unsorted A[0],A[1],A[2]................ A[n-1] and A[n] as input. Then the following steps are followed by storage merge sort algorithm to sort the values of an array.

Step1:Spliting the values of array
Divide the values into two equal 1/2
A[0],A[1],A[2].........A[n/2-1] & A[n/2]....... .................A[n-1], A[n]

Again divide two equal 1/2
A[0] a[1]A[2]..............A[(n/2-1)/2-1] & A[(n/2-1)/2]............A[n/2-1],
A[n/2].............A[(2n-1)/2-1] & a[(2n-1)/2].............A[n-1],A[n]
..........................................................................................................................
..........................................................................................................................
........................................................................................................................
A[0] & A[1] & A[2]& A[3],..............................................................A[n-1]& A[n]

Step2:Mergesets of two values, sort the values and store into a different array

A[0],A[1] & A[2],A[3]&..................................................................&A[n-1],A[n]
If A[1]A[n]
then
A[1]A[0],A[2]A[3],...............................................................................A[n]A[n-1]
Step3:Merge sets of four values, sort the values and store into a different array
A[2] A[1] A[0] A[3],...................................................................................A[n-1]
..................................................................................................................
..................................................................................................................
.................................................................................................................
Step3:Merge n values, sort the values and store into a different array
A[2]A[6]......................................................................................................A[n-5]

Where n must be even number.

Steps of Merge Sort:

Say unsorted an array values are:

12,9,4,99,120,1,3,10



The code of the program :

public class ExtraStorageMergeSort{
public static void main(String a[]){
int i;
int array[] = {12,9,4,99,120,1,3,10};
int array1[] = new int[array.length];
System.out.println("\n\n RoseIndia\n\n");
System.out.println(" Extra Strorage Space Merge Sort\n\n");
System.out.println("Values Before the sort:\n");
for(i = 0; i < array.length; i++)
System.out.print( array[i]+" ");
System.out.println();
mergeSort_srt(array,0, array.length-1,array1);
System.out.print("Values after the sort:\n");
for(i = 0; i <array.length; i++)
System.out.print(array1[i]+" ");
System.out.println();
System.out.println("PAUSE");
}

public static void mergeSort_srt(int array[], int low, int high, int array1[]){
if(low >= high) {
return;
}

int middle = (low+high) / 2;
mergeSort_srt(array, low, middle, array1);
mergeSort_srt(array, middle+1, high, array1);
int k, t_low = low, t_high = middle+1;
for(k = low; k <= high; k++)
if ((t_low <= middle) && ((t_high > high) || (array[t_low] <
array[t_high]))) {
array1[k] = array[t_low++];
}
else {
array1[k] = array[t_high++];
}
for(k = low; k <= high; k++) {
array[k] = array1[k];
}
}
}

Output of the example:

C:\array\sorting>javac ExtraStorageMergeSort.java
C:\array\sorting>java ExtraStorageMergeSort
       RoseIndia
       Extra Strorage Space Merge Sort
Values Before the sort:
12 9 4 99 120 1 3 10

Values after the sort:
1 3 4 9 10 12 99 120

Merge Sort In Java

Introduction

In this example we are going to sort integer values of an array using merge sort.

In merge sorting algorithm unsorted values are divided into two equal parts iteratively. Then merge both parts and sort it. Then again merge the next part and sort it. Do it iteratively
until the values are not in sorted order. In merge sorting the number of elements must be even. The merge sorting is invented by John von Neumann in 1945 .
The complexity of the merge sorting is in worst-case O(n log n) and in average case O(n log n).

Code description:
In merge sort split the array values in halves recursively until each half has only single element. Merge the two 1/2 values together and sort the values. Do same steps iteratively until the values are not sorted.

Working of merge sort algorithm:

Say we have an array unsorted A[0],A[1],A[2]................ A[n-1] and A[n] as input. Then the following steps are followed by merge sort algorithm to sort the values of an array.

Step1:Spliting the values of array
Divide the values into two equal 1/2
A[0],A[1],A[2].........A[n/2-1] & A[n/2]....... .................A[n-1], A[n]

Again divide two equal 1/2
A[0] a[1]A[2]..............A[(n/2-1)/2-1] & A[(n/2-1)/2]............A[n/2-1],
A[n/2].............A[(2n-1)/2-1] & a[(2n-1)/2].............A[n-1],A[n]
..........................................................................................................................
..........................................................................................................................
........................................................................................................................
A[0] & A[1] & A[2]& A[3],..............................................................A[n-1]& A[n]

Step2:Merge two values and sort the values

A[0],A[1] & A[2],A[3]&..................................................................&A[n-1],A[n]
If A[1]A[n]
then
A[1]A[0],A[2]A[3],...............................................................................A[n]A[n-1]
Step3:Merge four values and sort the values
A[2] A[1] A[0] A[3],...................................................................................A[n-1]
..................................................................................................................
..................................................................................................................
.................................................................................................................
Step3:Merge n values and sort the values
A[2]A[6]......................................................................................................A[n-5]

Where n must be even number.

Steps of Merge Sort:

Say unsorted an array values are:

12,9,4,99,120,1,3,10


The code of the program :

public class mergeSort{
public static void main(String a[]){
int i;
int array[] = {12,9,4,99,120,1,3,10};
System.out.println("\n\n RoseIndia\n\n");
System.out.println(" Selection Sort\n\n");
System.out.println("Values Before the sort:\n");
for(i = 0; i < array.length; i++)
System.out.print( array[i]+" ");
System.out.println();
mergeSort_srt(array,0, array.length-1);
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 mergeSort_srt(int array[],int lo, int n){
int low = lo;
int high = n;
if (low >= high) {
return;
}

int middle = (low + high) / 2;
mergeSort_srt(array, low, middle);
mergeSort_srt(array, middle + 1, high);
int end_low = middle;
int start_high = middle + 1;
while ((lo <= end_low) && (start_high <= high)) {
if (array[low] < array[start_high]) {
low++;
} else {
int Temp = array[start_high];
for (int k = start_high- 1; k >= low; k--) {
array[k+1] = array[k];
}
array[low] = Temp;
low++;
end_low++;
start_high++;
}
}
}
}

Output of the example:

C:\array\sorting>javac mergeSort.java
C:\array\sorting>java mergeSort
       RoseIndia
       Selection Sort
Values Before the sort:
12  9  4  99  120  1  3  10
Values after the sort:
1 3 4 9 10 12 99 120

Insertion Sort In Java

Introduction

In this example we are going to sort integer values of an array using insertion sort.

Insertion sorting algorithm is similar to bubble sort. But insertion sort is more efficient than bubble sort because in insertion sort the elements comparisons are less as compare to bubble sort. In insertion sorting algorithm compare the value until all the prior elements are lesser than compared value is not found. This mean that the all previous values are lesser than compared value. This algorithm is more efficient than the bubble sort .Insertion sort is a good choice for small values and for nearly-sorted values. There are more efficient algorithms such as quick sort, heap sort, or merge sort for large values .
Positive feature of insertion sorting:
1.It is simple to implement
2.It is efficient on (quite) small data values
3.It is efficient on data sets which are already nearly sorted.

The complexity of insertion sorting is O(n) at best case of an already sorted array and O(n2) at worst case .

Code description:
In insertion sorting take the element form left assign value into a variable. Then compare the value with previous values. Put value so that values must be lesser than the previous values. Then assign next value to a variable and follow the same steps relatively until the comparison not reached to end of array.
Working of insertion sorting:

The code of the program :

public class InsertionSort{
public static void main(String a[]){
int i;
int array[] = {12,9,4,99,120,1,3,10};
System.out.println("\n\n RoseIndia\n\n");
System.out.println(" Selection Sort\n\n");
System.out.println("Values Before the sort:\n");
for(i = 0; i < array.length; i++)
System.out.print( array[i]+" ");
System.out.println();
insertion_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 insertion_srt(int array[], int n){
for (int i = 1; i < n; i++){
int j = i;
int B = array[i];
while ((j > 0) && (array[j-1] > B)){
array[j] = array[j-1];
j--;
}
array[j] = B;
}
}
}

Output of the example:

C:\array\sorting>javac InsertionSort.java
C:\array\sorting>java InsertionSort
       RoseIndia
       Selection Sort
Values Before the sort:
12 9 4 99 120 1 3 10

Values after the sort:
1 3 4 9 10 12 99 120

Website Design by Mayuri Multimedia