Write algorithms for
internal class Program
{
static void Main()
{
int[] array = new int[] { 5, 56, 8, 9, 7, 2, 1, 5, 6, 8, 7, 1, 6, 5, 8, 4, 156, 849, 13, 56 };
Console.WriteLine("Buble Sort");
BubleSort(array);
DisplayArray(array);
Console.WriteLine("Quick Sort");
array = new int[] { 5, 56, 8, 9, 7, 2, 1, 5, 6, 8, 7, 1, 6, 5, 8, 4, 156, 849, 13, 56 };
QuickSort(array, 0, array.Length - 1);
DisplayArray(array);
Console.WriteLine();
Console.WriteLine("Linear Search");
Console.WriteLine(LinearSearch(array, 9));
Console.WriteLine(LinearSearch(array, 200));
Console.WriteLine();
Console.WriteLine("Binary Search");
Console.WriteLine(BinarySearch(array, 0, array.Length - 1, 9));
Console.WriteLine(BinarySearch(array, 0, array.Length - 1, 200));
Console.ReadKey();
}
static string BinarySearch(int[] array, int left, int right, int x)
{
if (right >= left)
{
int mid = left + (right - left) / 2;
if (array[mid] == x)
return $"Element {x} is present at index :{mid}";
if (array[mid] > x)
return BinarySearch(array, left, mid - 1, x);
return BinarySearch(array, mid + 1, right, x);
}
return $"No such element {x} exists in this array";
}
static string LinearSearch(int[] array, int x)
{
for (int i = 0; i < array.Length; i++)
{
if (array[i] == x)
return $"Element {x} is present at index :{i}";
}
return $"No such element {x} exists in this array";
}
static int Partition(int[] array, int left, int right)
{
int pivot = left - 1;
for (var i = left; i < right; i++)
{
if (array[i] < array[right])
{
pivot++;
int t = array[pivot];
array[pivot] = array[i];
array[i] = t;
}
}
pivot++;
int temp = array[pivot];
array[pivot] = array[right];
array[right] = temp;
return pivot;
}
static void QuickSort(int[] array, int left, int right)
{
if (left >= right)
{
return;
}
int pivot = Partition(array, left, right);
QuickSort(array, left, pivot - 1);
QuickSort(array, pivot + 1, right);
}
static void BubleSort(int[] array)
{
for (int i = 0; i < array.Length - 1; i++)
{
for (int j = 0; j < array.Length - i - 1; j++)
{
if (array[j] > array[j + 1])
{
int temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}
}
static void DisplayArray(int[] array)
{
for (int i = 0; i < array.Length; i++)
{
Console.Write($"{array[i]} ");
}
Console.WriteLine();
}
}
Comments
Leave a comment