Depoll.com: Programming, School, Life.

Sorting Algorithm Visualizations
By: David Eitan Poll

 

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:

Merge Sort

Description:
The Merge Sort is a list-splitting algorithm.  It recursively divides the list in two, until it reaches a base case of a list size of 1, which is inherently sorted.  Then, it performs a merge operation on the two parts of the list, which puts them together in order.  It is one of the more efficient sorts.

Efficiency: O(N*log(N))

Source:

public class MergeSort: SortMethod
{
   public override void sort(int[] list)
   {
      sort(list,0,list.Length-1);
   }
   private void sort(int[] list, int x1, int x2)
   {
      if(x1==x2) return;
      int middle=(x1+x2)/2;
      pause(middle);
      NumIterations++;
      sort(list,x1,middle);
      sort(list,middle+1,x2);
      merge(list,x1,middle,middle+1,x2);
   }
   private void merge(int[] list, int x1, int x2, int y1, int y2)
   {
      if(list[x2]<list[y1]) return;
      int i=0;
      int[] l1=new int[x2-x1+1];
      int[] l2=new int[y2-y1+1];
      int[] total=new int[l1.Length+l2.Length];
      int x;
      for(x=0;x<l1.Length;x++)
         l1[x]=list[x+x1];
      for(x=0;x<l2.Length;x++)
         l2[x]=list[x+y1];
      x=0;
      int y=0;
      while(i<total.Length)
      {
         if(y>=l2.Length||x<l1.Length&&l1[x]<l2[y])
            total[i++]=l1[x++];
         else total[i++]=l2[y++];
         NumComparisons++;
         NumIterations++;
      }
      for(x=0;x<total.Length;x++)
      {
         list[x1+x]=total[x];
         NumSwaps++;
         pause(x1+x);
      }
      pause(x1+x);
   }
   public override string ToString()
   {
      return "Merge Sort";
   }
}