Thursday, September 25, 2008

Sorting Algorithm with three popular method(c#)

some times we need to sort the array, it's general in our coding life. so there're three popular method i got. if you want, you can create a random array with Random class, i have mentioned below.
ok, let's go!

namespace SortingAlgorithm
{
public class CArray
{
private int[] arr;
private int upper;
private int numElements;
public CArray(int size)
{
arr = new int[size];
upper = size - 1;
numElements = 0;
}
public void Insert(int item)
{
arr[numElements] = item;
numElements++;
}
public void DisplayElements()
{
for (int i = 0; i <= upper; i++)
{
Console.Write(arr[i]+", ");
}
Console.WriteLine();
}
public void Clear()
{
for (int i = 0; i <= upper; i++)
{
arr[i] = 0;
numElements = 0;
}
}
//Bubble Sort
public void BubbleSort()
{
int temp;
//record how many times in this sort
int SortTimes = 0;
for (int i = upper; i >= 1; i--)
{
for (int j = 0; j <= i - 1; j++)
{
if (arr[j] > arr[j + 1])
{
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
SortTimes++;
}
}
Console.WriteLine(SortTimes);
}
//Selection Sort
public void SelectionSort()
{
int min;
int temp;
//record how many times in this sort
int SortTimes = 0;
for (int i = 0; i <= upper; i++)
{
min = i;
for (int j = i + 1; j <= upper; j++)
{
if (arr[min] > arr[j])
{
min = j;
}
SortTimes++;
}
temp = arr[i];
arr[i] = arr[min];
arr[min] = temp;
}
Console.WriteLine(SortTimes);
}
//Insertion Sort
public void InsertionSort()
{
int inner, temp;
//record how many times in this sort
int SortTimes = 0;
for (int i = 1; i <= upper; i++)
{
temp = arr[i];
inner = i;
while (inner > 0 && arr[inner - 1] >= temp)
{
arr[inner] = arr[inner - 1];
inner -= 1;
SortTimes++;
}
arr[inner] = temp;
}
Console.WriteLine(SortTimes);
}
}
class Program
{
static void Main(string[] args)
{
CArray nums = new CArray(10);
Random rnd = new Random(100);
for (int i = 0; i < 10; i++)
{
//create random number
nums.Insert((int)(rnd.NextDouble()*100));
}
Console.WriteLine("before sorting...");
nums.DisplayElements();
//Console.WriteLine("during bubble sorting...");
//nums.BubbleSort();
//Console.WriteLine("during selection sorting...");
//nums.SelectionSort();
Console.WriteLine("during Insertion sorting...");
nums.InsertionSort();
Console.WriteLine("after sorting...");
nums.DisplayElements();
}
}
}

No comments: