Code Snippets

  

Java Source Code


Welcome to Dream.In.Code
Become a Java Expert!

Join 137,188 Java Programmers for FREE! Get instant access to thousands of Java experts, tutorials, code snippets, and more! There are 2,329 people online right now. Registration is fast and FREE... Join Now!





Heap Sort (array representation)

A Java implementation of the heap sorting algorithm. This version uses an array to represent the heap. Uses a binary representation of the number of elements currently in the heap to find the pathway to the next insertion/removal site.

Submitted By: Dark_Nexus
Actions:
Rating:
Views: 769

Language: Java

Last Modified: August 29, 2008
Instructions: The is really a heap with a Sort method. The insert method will add an item to the heap in its proper position, and the pop method will remove a node from the heap and then re-balance the heap. The Sort method takes an array of Integer's and then passes that array through the heap sorting algorithm. The resulting sorted array will then be returned.

Snippet


  1. /**
  2. * For any element, i, in a list of size n, the following is true:
  3. *    -Parent element index = i/2 (floor(i))
  4. *    -Left child element index = 2i
  5. *    -Right child element index = 2i + 1
  6. */
  7.  
  8. import java.util.*;
  9. import java.lang.*;
  10.  
  11. class HeapSort {
  12.         private ArrayList<Integer> heap;        //Array containing the heap
  13.         private int length;                      //Current length of the heap;
  14.  
  15.         /**
  16.         * Calculates the index of the left child of the passed parent
  17.         * @param parent parent node to find left child for
  18.         * @return index of the left child of the passed parent
  19.         */
  20.         private int getLeftIndex(int parent) {
  21.                 return (2 * parent);
  22.               }
  23.  
  24.         /**
  25.         * Calculates the index of the right child of the passed parent
  26.         * @param parent parent node to find the right child for
  27.         * @return index of the right child of the passed parent
  28.          */
  29.               private int getRightIndex(int parent) {
  30.                 return ((2 * parent) + 1);
  31.               }
  32.  
  33.         /**
  34.         * Calculates the index of the parent node for the passed node
  35.         * @param node node to find the parent of
  36.         * @return index of the parent node of the passed node
  37.         */
  38.         private int getParentIndex(int node) {
  39.                 return (node / 2);
  40.               }
  41.  
  42.         /**
  43.         * Returns the value stored at the passed index
  44.         * @param index index to look for a value
  45.         * @return the value stored at the passed index
  46.         */       
  47.         private Integer getValueAtIndex(int index) {     
  48.                 return heap.get(index - 1);
  49.               }
  50.  
  51.         /**
  52.         * Swaps the values stored at the two passed indecies
  53.         * @param index_a first index to be used in the swap
  54.         * @param index_b second index to be used in the swap
  55.         */
  56.         private void swap(int index_a, int index_b) {
  57.                       //Convert indecies to an n-1 scheme
  58.                     index_a--;
  59.                     index_b--;
  60.  
  61.                     Integer tmp = heap.get(index_a);
  62.                     heap.set(index_a,heap.get(index_b));
  63.                     heap.set(index_b,tmp);
  64.              }           
  65.  
  66.         /**
  67.         * Inserts a the passed value into the list, and then
  68.         * percolates that number upwards accordingly
  69.         * @param value value to be inserted into the heap
  70.         */
  71.         private void insert(Integer value) {
  72.                 heap.add(value);
  73.  
  74.                 int current = ++length;                        //Set current to length + 1
  75.                 int parent = getParentIndex(current);        //Get index of the parent element
  76.  
  77.                     //While the current index is not the head, and the parent is greater than the child
  78.                     while ((current > 1) && (getValueAtIndex(current) <= getValueAtIndex(parent))) {
  79.                                swap(current,parent);                        //Swap the values
  80.                         current = parent;                             //Move current index to parent index
  81.                         parent = getParentIndex(current);       //Re-calculate parent index from current
  82.                       }
  83.               }
  84.  
  85.         /**
  86.         * Pops the head of the heap, and then moves the last value addded to the top
  87.         * of the heap.  Finally, that value is percolated downwards accordingly
  88.         * @return head of the heap
  89.         */
  90.               private Integer pop() {
  91.                 Integer ret = getValueAtIndex(1);        //Value to be returned
  92.  
  93.                    int current = 1;                        //Index to begin percolating
  94.                    heap.set(0,getValueAtIndex(length));        //Move last value added to the head
  95.                    heap.remove(--length);                        //Remove the last value added
  96.  
  97.                 //While a left child exists from the current
  98.                     while (getLeftIndex(current) <= length) {
  99.                         int left = getLeftIndex(current);          //Calculate the left child's index
  100.                         int right = getRightIndex(current);        //Calculate the right child's index
  101.                         int move = left;                          //Index where the percolating number will move next
  102.  
  103.                                //If the left child is larger than the right child
  104.                         if ((right <= length) && (getValueAtIndex(left) > getValueAtIndex(right))) {
  105.                                 move = right;        //Set the next move to the right child
  106.                         }
  107.  
  108.                         //If the parent is greater than the lesser of the two children
  109.                           if (getValueAtIndex(current) >= getValueAtIndex(move)) {
  110.                                 swap(current,move);      //Swap the parent with the lesser of the two children
  111.                         }
  112.  
  113.                           current = move;      //Set current index to the position moved to
  114.                     }     
  115.  
  116.                     return ret;        //Return top of the heap
  117.               }
  118.  
  119.         /**
  120.         * Will traverse the passed list element by element, adding each element it encounters
  121.         * to the heap.  The, until the heap is empty, it will pull the top, or minimum, value
  122.         * off of the heap and place it into a sorted list.
  123.         * @param unsorted unsorted set of integers to be sorted
  124.         * @return the sorted version of the passed unsorted integer set
  125.         */
  126.         public Integer[] Sort(Integer[] unsorted) {
  127.                 Integer[] sorted = new Integer[unsorted.length];
  128.  
  129.                 //Insert each number in the list into the heap
  130.                 for (int i = 0;i < unsorted.length;i++) {
  131.                         insert(list[i]);
  132.                 }
  133.  
  134.                 //Remove the smallest value from the heap until the heap is empty
  135.                 for (int i = 0;i < unsorted.length;i++) {
  136.                         sorted[i] = pop();
  137.                 }
  138.  
  139.                     return sorted;
  140.               }
  141.  
  142.         /**
  143.         * Default constructor for this class
  144.         */
  145.         public HeapSort() {
  146.                 length = 0;
  147.                        heap = new ArrayList();
  148.               }
  149. }
  150.  
  151.  

Copy & Paste


Comments


There are currently no comments for this snippet. Be the first to comment!

Add comment


You must be registered and logged on to </dream.in.code> to leave comments.





Live Java Help!

Java Tutorials

Reference Sheets

Java Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month