|
Home
Download
Screenshots
Adding your sorts
Algorithms
-Bubble Sort
-Comb Sort
-Gnome Sort
-Heap Sort
-Insertion Sort
-Merge Sort
-Odd/Even Sort
-Quick Sort
-Quick Sort with Bubble Sort
-Radix Sort
-Rob (Random) Sort
-Selection Sort
-Shaker Sort
-Shear Sort
-Shell Sort
Donation:
|
Heap Sort
Description:
The Heap Sort algorithm is just what it says. First, it turns the
list into a heap, then begins removing the top of the heap and
re-heaping. This results in a sorted list. Hooray!
It's among the more efficient sort algorithms.
Efficiency: O(N*log(N))
Source:
public class AlternativeHeapSort:
SortMethod
{
public override string ToString()
{
return "Alternative Heap Sort";
}
public override void sort(int[] list)
{
sortIt(list);
pause();
}
private void heapIt(int[] list)
{
int index=1;
while(index<list.Length)
{
int myI=index;
while(indexOfParent(myI)!=-1 &&
list[indexOfParent(myI)]<list[myI])
{
NumComparisons++;
NumIterations++;
swap(list,indexOfParent(myI),myI);
pause(myI,indexOfParent(myI));
myI=indexOfParent(myI);
}
index++;
}
}
private void sortIt(int[] list)
{
heapIt(list);
int lastDone=list.Length-1;
while(lastDone>0)
{
NumIterations++;
swap(list,0,lastDone);
reheapDown(list,0,lastDone--);
}
}
private void reheapDown(int[] list, int index,int last)
{
int left=-1;
int right=-1;
try
{
if(index*2+1<last)
left=list[index*2+1];
if(index*2+2<last)
right=list[index*2+2];
}
catch{}
int cur=list[index];
while(cur<left||cur<right)
{
NumIterations++;
NumComparisons+=2;
left=-1;
right=-1;
try
{
if(index*2+1<last)
left=list[index*2+1];
if(index*2+2<last)
right=list[index*2+2];
}
catch{}
NumComparisons++;
if(left>=right&&left>list[index])
{
swap(list,index,index*2+1);
pause(index,index*2+1,-1,-1,last);
index=index*2+1;
}
else if(right>left&&right>list[index])
{
swap(list,index,index*2+2);
pause(index,index*2+2,-1,-1,last);
index=index*2+2;
NumComparisons++;
}
cur=list[index];
}
}
private int indexOfParent(int node)
{
if(node==0) return -1;
return (node-1)/2;
}
} |
|