In: Computer Science
Write Insertion Sort and Bubble Sort Program for C# also write their algorithm and Explain their working.
1.Bubble sort in C#
using System;
public class BubbleShort
{
public static void Main(string[] args)
{
int[] var = { 4, 0, 1, 6, -2, 7, 5 };
int t;
Console.WriteLine("Original :");
foreach (int b in var)
Console.Write(b + " ");
//Logic for bubble sorting starts here
for (int q = 0; q <= var.Length - 2; q++)
{
for (int r = 0; r <= var.Length - 2; r++)
{
if (var[r] > var[r + 1])
{
t = var[r + 1];
var[r + 1] = var[r];
var[r] = t;
}
}
}
//To print the bubble sorted array
Console.WriteLine("\n"+"Bubble Sorted array :");
foreach (int b in var)
Console.Write(b + " ");
Console.Write("\n");
}
}
2.Insertion sort in C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
class Insertion_Sort
{
static void Main(string[] args)
{
int[] arr = new int[5] { 3, 102, 73, 39, 69 };
int i;
Console.WriteLine("The Original Array is :");
for (i = 0; i < 5; i++)
{
Console.WriteLine(arr[i]);
}
//method of insertion sort calls here
insertionsort(arr, 5);
Console.WriteLine("The processed Sorted Array is :");
for (i = 0; i < 5; i++)
Console.WriteLine(arr[i]);
Console.ReadLine();
}
// Method for insertion sort
static void insertionsort(int[] datains, int n)
{
int i, j;
for (i = 1; i < n; i++)
{
int itemins = datains[i];
int ins = 0;
for (j = i - 1; j >= 0 && ins != 1; )
{
if (itemins < datains[j])
{
datains[j + 1] = datains[j];
j--;
datains[j + 1] = itemins;
}
else ins = 1;
}
}
}
}