Home | Ajax | BioInformatics | Dojo | EAI | EJB | Hibernate | J2ME | Java | Java Glossary | Java Servlets | JavaScript | Jboss | JDBC | JDO | Jmeter | JSF | JSP | JUnit | Maven | MySQL | Spring Framework | SQL | Struts | Technology | WAP | Web Services | XML


 
  
 
Programming Tutorials: Ajax | Articles | JSP | Bioinformatics | Database | Free Books | Hibernate | J2EE | J2ME | Java | JavaScript | JDBC | JMS | Linux | MS Technology | PHP | RMI | Web-Services | Servlets | Struts | UML
 

 
Facing Programming Problem?
Ask Questions?, Browse Latest Questions, Question-Answer Guidelines
Java
  JDO Tutorials
  EAI Articles
  Struts Tutorials
  Java Tutorials
  Java Certification
  Java Applet
Questions
Comments

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
C:\array\sorting>_

Download this example.

                         

Leave your comment:

Name:

Email:

URL:

Title:

Comments:


Enter Code:

Audio Version
Reload Image
 

Note: Emails will not be visible or used in any way, and are not required. Please keep comments relevant. Any content deemed inappropriate or offensive may be edited and/or deleted.

No HTML code is allowed. Line breaks will be converted automatically. URLs will be auto-linked. Please use BBCode to format your text.

Add This Tutorial To:
  Del.icio.us   Digg   Google   Spurl   Blink   Furl   Simpy   Y! MyWeb 

Current Comments

2 comments so far (
post your own) View All Comments Latest 10 Comments:

this web page is very useful any body those who are beginner of data structures in java

Posted by sridhar on Tuesday, 02.19.08 @ 22:41pm | #49114

Very nice tutorial. Is it possible to make this vizual, using swing classes instead standard output? I apreciate it if you can give me some links with swing tutorial for heap sorting algorithm

Posted by ludi on Tuesday, 12.18.07 @ 02:37am | #42762

Latest Searches:
type casting
difference b/w pass by
interface examples
ChatServer
display the sum of 20
DB
javamail spring
insert fields blob
java card framework
Photoshop Drawing Draw
SimpleDateFormat
Javascript Mouse Trick
jQuery To Slide Effect
JSF selectBooleanCheck
scrollbar with event
A�������
SSI
database through jsp
insert the data into m
program to check input
Merge Sort In Java
dirt
get double value from
array element in php
struts packages
Photoshop Digital Art
ask user to enter valu
convert java.sql.Time
rfc
photo restoration tuto
Linux Caixa MÄ??Ã?Ä???
build.xml
how to write DAO class
CSS CSS Creating and L
code for simple calcul
The End of Spyware
panelGrid
Combattons la programm
JFrame.extendedState
covert uppercase to lo
what is serialization
capture image j2me
JSP templates. Use JSP
Photoshop Color Painti
xls
5. Create an applet fo
jsp bean get property
java date compare exam
Display name of system
<s:include>
java cancel button
awt jdbc
jdbc insert
jsf upload
FileInputStream
permutation program
netbeans jsp jdbc
TextArea Frame in Java
days difference
calculate trapezium
java.lang.ArrayIndexOu
retreive numerical val
They just work
calculator
stored procedure debug
for loop tutorial
Autoboxing
what is rfc
Photoshop Animation Sh
API
count line
how to save blob to fi
linked list
Registration code in j
line count
cell width POI
types of webserver
C and Cpp Introduction
JConfig
Wireless
Java String toLowerCase Example
Java String toCharArray Example
Java String substring Example
Java String indexOf Example
Java String startsWith Example
Java String hashCode Example
Java String matches Example
Java String length Example
Java String lastIndexOf Example
Java String isEmpty Example
Java String equalsIgnoreCase Example
Java String equals Example
Java String endsWith Example
Java String copyValueOf Example
Java String contentEquals Example
  EAI Articles
  Java Certification
Tell A Friend
Your Friend Name
Search Tutorials

 

 
 
Browse all Java Tutorials
Java JSP Struts Servlets Hibernate XML
Ajax JDBC EJB MySQL JavaScript JSF
Maven2 Tutorial JEE5 Tutorial Java Threading Tutorial Photoshop Tutorials Linux Technology
Technology Revolutions Eclipse Spring Tutorial Bioinformatics Tutorials Tools SQL
 

Home | JSP | EJB | JDBC | Java Servlets | WAP  | Free JSP Hosting  | Search Engine | News Archive | Jboss 3.0 tutorial | Free Linux CD's | Forum | Blogs

About Us | Advertising On RoseIndia.net  | Site Map

India News

Indian Software Development Company | iPhone Development Company in India | Java Training Delhi | Java Training at Noida |

Send your comments, Suggestions or Queries regarding this site at roseindia_net@yahoo.com.

Copyright © 2008. All rights reserved.