76 lines
1.8 KiB
C#
76 lines
1.8 KiB
C#
namespace Sortering
|
|
{
|
|
public static class Sort
|
|
{
|
|
public static void InsertionSort(int[] array)
|
|
{
|
|
int i, n;
|
|
int length = array.Length;
|
|
int temp;
|
|
|
|
if (length < 2) return;
|
|
|
|
for (n=1; n<length; n++)
|
|
{
|
|
temp = array[n];
|
|
i = n - 1;
|
|
|
|
while (i >= 0 && array[i] > temp)
|
|
{
|
|
array[i+1] = array[i];
|
|
i--;
|
|
}
|
|
|
|
array[i+1] = temp;
|
|
}
|
|
}
|
|
|
|
public static void BubbleSort(int[] array)
|
|
{
|
|
for (int m = array.Length-1; m > 0; m--)
|
|
{
|
|
for (int n = 0; n<m; n++)
|
|
{
|
|
if (array[n] > array[n + 1])
|
|
{
|
|
int temp = array[n];
|
|
array[n] = array[n+1];
|
|
array[n+1] = temp;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
public static int SequentialFind(int[] haystack, int needle)
|
|
{
|
|
for (int i = 0; i < haystack.Length; i++)
|
|
{
|
|
if (haystack[i] == needle)
|
|
{
|
|
return i;
|
|
}
|
|
}
|
|
|
|
return -1;
|
|
}
|
|
|
|
public static int BinaryFind(int[] haystack, int needle)
|
|
{
|
|
int min = 0;
|
|
int max = haystack.Length -1;
|
|
int i = -1;
|
|
|
|
while (min <= max && i == -1)
|
|
{
|
|
int mid = (min + max) / 2;
|
|
|
|
if (needle > haystack[mid]) min = mid + 1;
|
|
else if (needle < haystack[mid]) max = mid - 1;
|
|
else i = mid;
|
|
}
|
|
|
|
return i;
|
|
}
|
|
}
|
|
}
|