Skip to content

Instantly share code, notes, and snippets.

Created April 1, 2016 11:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/178e859911871a35021a9387766e86e8 to your computer and use it in GitHub Desktop.
Save anonymous/178e859911871a35021a9387766e86e8 to your computer and use it in GitHub Desktop.
Test different sorting algorithm's
public static int count = 0;
public void MySort(int[] arr){
count = 0;
int n = arr.Length;
for (int i=0; i<n; i++)
for (int j=i; j>0; j--)
{
count++;
if (arr[j].CompareTo(arr[j-1])<0)
MySortExchange(arr,j,j-1);
else break;
}
}
public void MySelectionSort(int[] arr){
count = 0;
int n = arr.Length;
for (int i=0; i<n; i++){
int min = i; // find the minimum
for (int j=i+1; j<n; j++)
{
count++;
if (arr[j].CompareTo(arr[min])<0) min = j;
}
MySortExchange(arr,i,min);
}
}
public void MyInsertionSort(int[] arr){
count = 0;
int n = arr.Length;
for (int i=0; i<n; i++)
for (int j=i; j>0; j--) // Compare current position with position before
{
count++;
if (arr[j].CompareTo(arr[j-1])<0) //Finding minimum of this 2 elements and
MySortExchange(arr,j,j-1); //swap them!
else break;
}
}
public void MyShellSort(int[] arr){
count = 0;
int n = arr.Length;
int h = 1;
while (h<n/3) h=3*h+1; // 3x + 1 increment sequence
while (h>=1){
for (int i=h; i<n; i++)
for (int j=i; j>=h&&(arr[j].CompareTo(arr[j-h])<0); j--)
{
count++;
MySortExchange(arr,j,j-h); //swap them - Insertion Sort
}
h = h/3; // move to next increment
}
}
public void MySortExchange(int[] arr, int i, int j){
int swap = arr[i];
arr[i] = arr[j];
arr[j] = swap;
}
public void MySortPrint(int[] arr){
foreach (int n in arr) Console.Write("{0} ", n);
Console.WriteLine();
}
int[] test = new int[] {8, 1, 10, 7, 55, 24, 43, 88, 2, 313, 81, 134, 85, 17, 89, 255, 77, 13, 243, 454, 574, 446, 544, 4};
Console.WriteLine("UnSorted array:");
MySortPrint(test);
//MySort(test);
//Console.WriteLine("MySort: Count = {0}", count);
//MySelectionSort(test);
//Console.WriteLine("Selection Sort: Count = {0}", count);
//MyInsertionSort(test);
//Console.WriteLine("Insertion Sort: Count = {0}", count);
MyShellSort(test);
Console.WriteLine("Shell Sort: Count = {0}", count);
Console.WriteLine("Sorted array:");
MySortPrint(test);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment