473,480 Members | 1,968 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

Generic heap sort algorithm B

11,448 Recognized Expert MVP
Welcome back to the Sorting article.

For completeness, so you can copy and paste this sorting utility straight
in your own private back of tricks, here is the entire class:

Expand|Select|Wrap|Line Numbers
  1. public final class HeapSort {
  2.  
  3.     private HeapSort() { } // no istances of this class possible
  4.  
  5.     // given a Sortable, build a heap starting at node i. There a n nodes in total
  6.     private static void heapify(Sortable s, int p, int n) {
  7.  
  8.         for (int r, l= (p<<1)+1; l < n; p= l, l= (p<<1)+1) {
  9.  
  10.             // l is the maximum of l and r, the two subnodes of p 
  11.             if ((r= l+1) < n && s.compare(l, r) < 0) l= r;
  12.  
  13.             // check if parent p is less than maximum l
  14.             if (s.compare(p, l) < 0) s.swap(p, l);
  15.             else break;
  16.         }
  17.  
  18.     // build a heap out of the Sortable in place
  19.     private static void phase1(Sortable s) {
  20.  
  21.         // heapify all the non-leaf nodes         
  22.         for (int n= s.length(), p= n/2; p >= 0; p--)
  23.             heapify(s, p, n);
  24.     }
  25.  
  26.     // sort the Sortable
  27.     private static void phase2(Sortable s) {
  28.  
  29.         for (int n= s.length(); --n > 0; ) {
  30.             s.swap(0, n);         // put the root element in its place
  31.             heapify(s, 0, n);     // and restore the heap again
  32.         }        
  33.     }
  34.  
  35.     // driver for the worked methods
  36.     public static Sortable sort(Sortable s) { 
  37.  
  38.         phase1(s);     // build initial heap
  39.         phase2(s);     // sort the sortable given the heap
  40.  
  41.         return s;     // return the Sortable for convenience
  42.     }
  43. }
  44.  
This class takes about one page of text in my VI text editor. Let's step back
a bit from this code and realize what we've just created: this sort algoritm is
very efficient and stable w.r.t. it's runtime. This implementation doesn't know
anything about what exactly needs to be sorted, i.e. it only uses the Sortable
interface.

The class is final and contains a private default constructor so there is no
way for anyone else to create an instance of a HeapSort object; because no such
object is needed: this class is a utility class with just functionality.

The first article explained a bit about the heap sort algorithm itself.
Now let's get back to our original problem: given the following two arrays:

Expand|Select|Wrap|Line Numbers
  1. String[] first= { "Fred", "Barney", "Wilma", "Betty", "Bambam", "Pebbles" };
  2. String[] last= { "Flintstone", "Rubble", "FlintStone", "Rubble", "Rubble", "Flintstone" };
  3.  
We have to create a Sortable that can return the number of first/last names, it
can compare two first names (for example) and it can swap two elements in both
the first and last name arrays. We need to sort these two array according to
the first name; the other array just needs to 'follow' i.e it last names must
correspond to the first names after the sort has finished.

Here's the complete example without many comments:

Expand|Select|Wrap|Line Numbers
  1. public class Flintstones implements Sortable {
  2.  
  3.     private String[] first;
  4.     private String[] last;
  5.  
  6.     public FlintStones(String[] first, String[] last) {
  7.  
  8.         this.first= first;
  9.         this.last = last;
  10.     }
  11.  
  12.     public int length() { // interface implementation
  13.  
  14.         return first.length; 
  15.     } 
  16.  
  17.     public int compare(int i, int j) { // interface implementation
  18.  
  19.         return first[i].compareTo(first[j]);
  20.     }
  21.  
  22.     private void swap (String[] s, int i, int j) { // private helper method
  23.  
  24.         String t= s[i]; s[i]= s[j]; s[j]= t;
  25.  
  26.     }
  27.     public void swap(int i, int j) { // interface implementation
  28.  
  29.         swap(first, i, j);
  30.         swap(last, i, j);
  31.     }
  32.  
  33.     public static void main(String[] args) {
  34.  
  35.         String[] first= { "Fred", "Barney", "Wilma", "Betty", "Bambam", "Pebbles" };
  36.         String[] last= { "Flintstone", "Rubble", "FlintStone", "Rubble", "Rubble", "Flintstone" };
  37.  
  38.         HeapSort.sort(new ArraySortable(first, last));
  39.  
  40.         for (int i= 0; i < first.length; i++)
  41.             System.out.println(first[i]+" "+last[i]);
  42.     }
  43. }
  44.  
So what was this 'Tip Of The Week' all about? It showed that you can sort not
just arrays or Lists, but anything that implements the Sortable interface. It
also showed some of the gory details of the heap sort algorithm.

If I don't get kicked out now I'd like to tell something about permutations
and combinations in a next Tip Of The Week and how they can be efficiently
generated without much hassle.

kind regards,

Jos
May 4 '07 #1
0 5428

Sign in to post your reply or Sign up for a free account.

Similar topics

3
7907
by: darth | last post by:
Does anyone have heap sorting with queue(doublely linked list) in C? I have heap sort with array but with queue, it's somewhat hard.
0
2001
by: Bonj | last post by:
hello this is a purely algorithmical question but if i have posted to an irrelevant group, apologies. can anyone point me at some good tutorials or info about the steps involved in creating a...
5
1535
by: songie D | last post by:
I am looking to write a very fast algorithm to merge ranges. e.g. if it was input the following ranges (1,3), (4,6), (9, 12) it should return exactly the same thing. However if it's passed (1, 5),...
1
3452
by: codergem | last post by:
The following code is for heap sort but its not working properly. According to my analysis the Logic is correct but still its not showing the correct output. Thanks. #include "stdafx.h"...
0
2718
by: Raj | last post by:
We are on a db2 v8.2 (fix 8) with DPF & intra parllelism. Below are sort related configuration settings ...
6
6936
by: Nick Valeontis | last post by:
I know how to use Icomparable. However, I can't figure out how to sort a generic linked list? (without writing the algorithm) Lets say I have something like this: class...
10
5570
by: Woody Ling | last post by:
In 32 bits DB2 environment, is it meaningful to set sheapthres larger than 256MB for the following case.. 1. Intra-parallel is ON 2. Intra-parallel is OFF
0
13271
by: JosAH | last post by:
Greetings, I was asked to write a Tip Of the Week; so here goes: a lot of topics are started here in this forum (and a lot of other forums too) mentioning a problem about sorting data. ...
5
1373
by: Alan | last post by:
I was wondering if anyone had design advice on this. . . . I am doing some mathematical operations looking at different metrics for data (in objects) I have captured. The object class has several...
9
8049
by: sophia.agnes | last post by:
Hi all, Is there a simple algorithm to implement in heapsort??? this is the program i found in my college D.S notebook #include<stdio.h> #include<stdlib.h> void heapsort (int, int);
0
7055
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
6920
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
7059
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
1
6758
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
7010
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
5362
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
3011
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
3003
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
572
muto222
php
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.