This is another sorting algorithm called heap sort that I wrote using Java programming language. The heap sort code is quiete complex but i tried my best to write it

130 Views
``````import java.io.*;

class heap

{
static void printArray(int[] a)

{
for (int i = 1; i < a.length; i++) System.out.print(" " + a[i]);
System.out.print("\n");
}

// Heap Sort Function to sort numerical values

public static void fnSortHeap(int array[], int arr_ubound){
int i=0, o=0;
int lChild=0, rChild=0, mChild=0, root=0, temp=0;
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;
}

public static void main (String args []) throws IOException
{
String get_value;
int n_value=0;

String strEntry;
int i=0;

int entry[] = new int[6];
System.out.println();
System.out.print("\t============================================\n");
System.out.print("\t========== Heap Sort Version 1.0 ===========\n");
System.out.print("\t===== By: Mr. Jake Rodriguez Pomperada =====\n");
System.out.print("\t============================================\n");

System.out.println();

for( i =1 ; i < entry.length; i++)

{

System.out.print("Enter number No. " + i +" : ");
entry[i] = Integer.parseInt(strEntry);
}
System.out.println();
System.out.println("== Original numbers ==>");
printArray(entry);

for(i=entry.length; i>1; i--){
fnSortHeap(entry, i-1 );
}

System.out.println("\n");
System.out.println("== Sorted numbers ==>");
printArray(entry);
System.out.println("\n");
System.out.print("\t====================================================\n");
System.out.print("\t=== Created By: Jake Rodriguez Pomperada,MAED-IT ===\n");
System.out.print("\t====================================================\n");
}

} // End of Code``````