sorting

A sorting algorithm is an algorithm that puts elements of a list in a certain order. - Wikipedia

bubble sort

for (int i = 0; i < data.Length; i++)
    for (int j = 0; j < data.Length - 1; j++)
      if (data[j] > data[j+1])
      {
        tmp = data[j]
        data[j] = data[j+1]
        data[j + 1] = tmp
      }

insertion sort

for (int i = 0; i < data.Length; i++) {
  int j = i;
  while (j  > 0 && data[i] < data[j-1])
    j--;
  int tmp = data[i];
  for (int k = i; k > j; k--)
  {
    data[k] = data[k -1];
  }
  data[j] = tmp;
}

library sort

merge sort

heap sort

Heap h = new Heap();
  for (int i = 0; i < data.Length; i++)
    h.Add(data[i]);
  int[] result = new int[data.length];
  for (int i = 0; i < data.Length; i++)
    data[i] = h.RemoveLowest();

quick sort

Array quickSort(Array data)
  {
    if (data.Length <= 1)
      return;
    middle = Array[data.Length / 2];
    Array left = new Array();
    Array right = new Array();
    for (int i=0; i < data.Length; i++)
    {
      if(i != data.Length / 2)
      {
        if (data[i] <= middle)
          left.Add(data[i]);
        else
          right.Add(data[i]);
      }
    }
    return combine(quickSort(left), middle, quickSort(right));
  }
comments powered by Disqus