Bubble Sort
Below image will describe how bubble sort code work when code execute in loop, below pictures are self explanatory for algorithm steps.
C# Codepublic int[] BubbleSort(int[] val)
{
bool flag = true;
int temp;
for (int i =0;(i<=val.Count()-1) && flag; i++)
{
flag = false;
for (int j = 0; j < val.Count()-1; j++)
{
if (val[j + 1] < val[j])
{
temp = val[j + 1];
val[j + 1] = val[j];
val[j] = temp;
flag = true;
}
}
}
return val;
}
Insertion Sort
Faster than bubble sort
C# Code
public int[] InsertionSort(int[] val)
{
for (int i = 0; i <= val.Count(); i++)
{
int temp = val[i];
int j = i - 1;
while (j >= 0 && val[j] < temp)
{
val[j + 1] = val[j];
j--;
}
val[j + 1] = temp;
}
return val;
}
No comments:
Post a Comment