Insertion Sort on an array of strings in C# - c#

If I have an array of strings, such as
string[] names = {"John Doe", "Doe John", "Another Name", "Name Another"};
How do I sort this array, using insertion sort?
Wikipedia has some examples: https://en.wikibooks.org/wiki/Algorithm_implementation/Sorting/Insertion_sort#C.23
static void InsertSort(IComparable[] array)
{
int i, j;
for (i = 1; i < array.Length; i++)
{
IComparable value = array[i];
j = i - 1;
while ((j >= 0) && (array[j].CompareTo(value) > 0))
{
array[j + 1] = array[j];
j--;
}
array[j + 1] = value;
}
}
and
static void InsertSort<T>(IList<T> list) where T : IComparable<T>
{
int i, j;
for (i = 1; i < list.Count; i++)
{
T value = list[i];
j = i - 1;
while ((j >= 0) && (list[j].CompareTo(value) > 0))
{
list[j + 1] = list[j];
j--;
}
list[j + 1] = value;
}
}
but it doesn't seem to work on my array of strings, unless I'm doing something wrong.
Would I not run
InsertSort(names); // like so?

Works fine for me:
class Program
{
static void Main()
{
string[] names = { "John Doe", "Doe John", "Another Name", "Name Another" };
InsertSort(names);
foreach (var item in names)
{
Console.WriteLine(item);
}
}
static void InsertSort(IComparable[] array)
{
int i, j;
for (i = 1; i < array.Length; i++)
{
IComparable value = array[i];
j = i - 1;
while ((j >= 0) && (array[j].CompareTo(value) > 0))
{
array[j + 1] = array[j];
j--;
}
array[j + 1] = value;
}
}
}
As expected it prints:
Another Name
Doe John
John Doe
Name Another

Here's my implementation:
public static void Swap<T>(ref T a, ref T b)
{
T t = a;
a = b;
b = t;
}
public static void InsertionSort<T>(this T[] a) where T : IComparable<T>
{
a.InsertionSort(Comparer<T>.Default.Compare);
}
public static void InsertionSort<T>(this T[] a, Comparison<T> c)
{
int n = a.Length;
for (int i = 1; i < n; ++i)
for (int k = i; k > 0 && c(a[k], a[k - 1]) < 0; --k)
Swap(ref a[k], ref a[k - 1]);
}

I do some class to do this:
public static class InsertionSort<T> where T : System.IComparable<T>
{
public static void Sort(ref T[] array)
{
T[] tmp = new T[array.Length];
tmp[0] = array[0];
for (int i = 1; i < array.Length; i++)
{
int place = FindProperPlace(tmp, array[i]);
ExpandArray(ref tmp, place);
tmp[place] = array[i];
}
array = tmp;
}
private static int FindProperPlace(T[] numbersArray, T number)
{
int j;
for (j = 0; j < numbersArray.Length; j++)
{
if (number.CompareTo(numbersArray[j]) < 0)
{
break;
}
}
return j;
}
private static void ExpandArray(ref T[] tmp, int place)
{
for (int i = tmp.Length - 1; i > place; i--)
{
tmp[i] = tmp[i - 1];
}
}
}

Related

Merge sort 2d array c#

I have task to create merge sort algorithm in c# for 2d array. Array looks like that
X1 Y1
X2 Y2
…
Xn Yn
I need to take array from file and sort the lines in ascending x order, also the program should check for the absence of pairs of coordinates with the same X values and at the same time different Y values, when array was sorted, the programm should write it in the file.
I had created algorithm for 1d array, but can't understand how to rewrite it for 2d array, here is my code, please help me
using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
class Program
{
//array merging
static void Merge(int[] num, int lowIndex, int middleIndex, int highIndex)
{
var left = lowIndex;
var right = middleIndex + 1;
var tempArray = new int[highIndex - lowIndex + 1];
var index = 0;
while ((left <= middleIndex) && (right <= highIndex))
{
if (num[left] < num[right])
{
tempArray[index] = num[left];
left++;
}
else
{
tempArray[index] = num[right];
right++;
}
index++;
}
for (var j = left; j <= middleIndex; j++)
{
for (var i=0;;) {
tempArray[index] = num[j];
index++; }
}
for (var j = right; j <= highIndex; j++)
{
for (var i = 0; ;)
{
tempArray[index] = num[j];
index++;
}
}
for (var j = 0; j < tempArray.Length; j++)
{
for(var i=0; ;)
{
num[lowIndex + j] = tempArray[j];
}
}
}
//merge sorting
static int[] MergeSort(int[] num, int lowIndex, int highIndex)
{
if (lowIndex < highIndex)
{
var middleIndex = (lowIndex + highIndex) / 2;
MergeSort(num, lowIndex, middleIndex);
MergeSort(num, middleIndex + 1, highIndex);
Merge(num, lowIndex, middleIndex, highIndex);
}
return num;
}
public static int[] MergeSort(int[] num)
{
return MergeSort(num, 0, num.Length - 1);
}
static void Main(string[] args)
{
Console.WriteLine("Merge sorting");
string[] lines = File.ReadAllLines(#"C:\Users\glebk\source\repos\ConsoleApp18\ConsoleApp18\file.txt");
int[,] num = new int[lines.Length, lines[0].Split(' ').Length];
for (int i = 0; i < lines.Length; i++)
{
string[] temp = lines[i].Split(' ',',');
for (int j = 0; j < temp.Length; j++)
{
num[i, j] = Convert.ToInt32(temp[j]);
Console.Write(num[i, j]+" ");
}
Console.ReadKey();
}
Console.WriteLine("Sorted array: {0}", string.Join(",", MergeSort(num)));
}
}`
The most direct way of doing it is replacing
tempArray[index] = num[left];
with something like this
static void CopyLine(int[,] destArr, int destIndex, int[,] sourceArr, int sourceIndex)
{
for (int i = 0; i < destArr.GetLength(1); ++i)
{
destArr[destIndex, i] = sourceArr[sourceIndex, i];
}
}
here is the whole code
static void CopyLine(int[,] destArr, int destIndex, int[,] sourceArr, int sourceIndex)
{
for (int i = 0; i < destArr.GetLength(1); ++i)
{
destArr[destIndex, i] = sourceArr[sourceIndex, i];
}
}
//array merging
static void Merge(int[,] num, int lowIndex, int middleIndex, int highIndex)
{
var left = lowIndex;
var right = middleIndex + 1;
var tempArray = new int[highIndex - lowIndex + 1, num.GetLength(1)];
var index = 0;
while ((left <= middleIndex) && (right <= highIndex))
{
if (num[left, 0] < num[right, 0])
{
CopyLine(tempArray, index, num, left);
left++;
}
else
{
CopyLine(tempArray, index, num, right);
right++;
}
index++;
}
for (var j = left; j <= middleIndex; j++)
{
CopyLine(tempArray, index, num, j);
index++;
}
for (var j = right; j <= highIndex; j++)
{
CopyLine(tempArray, index, num, j);
index++;
}
for (var j = 0; j < tempArray.GetLength(0); j++)
{
CopyLine(num, lowIndex + j, tempArray, j);
}
}
//merge sorting
static void MergeSort(int[,] num, int lowIndex, int highIndex)
{
if (lowIndex < highIndex)
{
var middleIndex = (lowIndex + highIndex) / 2;
MergeSort(num, lowIndex, middleIndex);
MergeSort(num, middleIndex + 1, highIndex);
Merge(num, lowIndex, middleIndex, highIndex);
}
}
public static void MergeSort(int[,] num)
{
MergeSort(num, 0, num.GetLength(0) - 1);
}
static void WriteArray(string description, int[,] arr)
{
Console.WriteLine(description);
for (int i = 0; i < arr.GetLength(0); i++)
{
for (int j = 0; j < arr.GetLength(1); j++)
{
Console.Write(arr[i, j] + " ");
}
Console.WriteLine();
}
Console.WriteLine();
}
static void Main(string[] args)
{
int[,] num = new int[,] { { 3, 5 }, { 1, 10 }, { 7, 3 }, { 2, 1 }, { 5, 2 } };
WriteArray("Original array:", num);
MergeSort(num);
WriteArray("Sorted array:", num);
Console.ReadKey();
}
There are also other options, you can fuse two int values into one long value and sort it as 1D array. But it would need additional steps.

How do I implement a step counter into a bubble sort?

I am trying to implement a step counter into my bubble sort algorithm, but I don't know how to display the counter at the end of the sorting algorithm. If anyone could explain how I should go about this that would be great. Thank You.
My current code: (Bubble Sort):
static int[] bubbleSort(int[] arr, int n)
{
int stepCount = 0; // <- Counter to return and display
for (int i = 0; i < n - 1; i++)
{
for (int j = 0; j < n - 1 - i; j++)
{
if (arr[j + 1] < arr[j])
{
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
stepCount++;
}
}
return arr;
}
public static void DisplayArrayBubble(int[] arr)
{
foreach (int i in arr)
{
Console.Write(i.ToString() + " ");
}
}
Why not just return int - number of steps? I.e.
// arr : will be sorted
// return : number of steps
static int bubbleSort(int[] arr) {
if (null == arr)
return 0;
int stepCount = 0;
for (int i = 0; i < arr.Length - 1; i++)
for (int j = 0; j < arr.Length - 1 - i; j++)
if (arr[j + 1] < arr[j]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
stepCount += 1;
}
return stepCount;
}
Demo:
int[] sample = new int[] {1, 5, 4, 3, 2, 7};
int steps = bubbleSort(sample);
Console.WriteLine($"Sorted [{string.Join(", ", sample)}] in {steps} steps");
Outcome:
Sorted [1, 2, 3, 4, 5, 7] in 6 steps
There a plethora of ways but one is to make a custom class to hold both pieces of information that you need:
public class BubbleObject
{
public int[] arr { get; set; }
public int stepCount { get; set; }
}
Then adjust the code you have to use that object:
static BubbleObject bubbleSort(int[] arr, int n)
{
int stepCount = 0;
for (int i = 0; i < n - 1; i++)
{
for (int j = 0; j < n - 1 - i; j++)
{
if (arr[j + 1] < arr[j])
{
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
stepCount++;
}
}
BubbleObject bo = new BubbleObject() { arr=arr, stepCount=stepCount}
return bo;
}
public static void DisplayArrayBubble(BubbleObject bo)
{
Console.WriteLine("Number of Steps = " + bo.stepCount);
foreach (int i in bo.arr)
{
Console.Write(i.ToString() + " ");
}
}
That should do it. There are other ways as well.

Sequence of marching chars in 2 strings

I have to write searching algorithm, For example I have to compare str="giorgi" to str2="grigol". I'm trying to find longest matching sequence of chars, so that the order of chars is the same and string which I should get is "grg"... with this c# code I'm getting "grig".
int k=0;
string s="";
string str = "giorgi";
string str2 = "grigol";
for(int i=0;i<str.Length;i++)
{
for (int j = k; j < str2.Length; j++)
{
if (str[i] == str2[j])
{
s += str2[k];
k++;
goto endofloop;
}
}
endofloop:;
}
Console.WriteLine(s);
The solution:
using System;
class GFG
{
/* Returns length of LCS for X[0..m-1], Y[0..n-1] */
static int lcs( char[] X, char[] Y, int m, int n )
{
int [,]L = new int[m+1,n+1];
/* Following steps build L[m+1][n+1]
in bottom up fashion. Note
that L[i][j] contains length of
LCS of X[0..i-1] and Y[0..j-1] */
for (int i = 0; i <= m; i++)
{
for (int j = 0; j <= n; j++)
{
if (i == 0 || j == 0)
L[i, j] = 0;
else if (X[i - 1] == Y[j - 1])
L[i, j] = L[i - 1, j - 1] + 1;
else
L[i, j] = GFG.max(L[i - 1, j], L[i, j - 1]);
}
}
return L[m, n];
}
static int max(int a, int b)
{
return (a > b)? a : b;
}
}
And now the program to test it:
public static void Main()
{
String s1 = "giorgi";
String s2 = "grigol";
char[] X=s1.ToCharArray();
char[] Y=s2.ToCharArray();
int m = X.Length;
int n = Y.Length;
Console.Write("Length of LCS is" + " " +lcs( X, Y, m, n ) );
}
}

2d array to 1d array C#

I've got two algorithms converting random 2d arrays (m х n or m х m) to 1d array. I'm wondering if there is a way to make them work als in the opposite direction and convert the result to 1d array saving the order of numbers. Here is the full code of my program and a picture to see how both of my algorithms work.enter image description here
Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using static System.Math;
namespace MyProgram
{
public class Program
{
public static void Main(string[] args)
{
Console.Write("Enter number of rows:");
int n = int.Parse(Console.ReadLine());
Console.Write("Enter number of columns:");
int m = int.Parse(Console.ReadLine());
int[] arr1 = new int[n * m];
int[,] arr2 = new int[n, m];
int choice;
do
{
Console.WriteLine("Select option:");
Console.WriteLine("\t1: Diagonal");
Console.WriteLine("\t2: Spiral");
Console.WriteLine("\t3: Exit");
Console.Write("Your selection: ");
choice = int.Parse(Console.ReadLine());
switch (choice)
{
case 1:
{
SetArray(arr2);
PrintArray(arr2);
Diagonal(arr2, arr1);
PrintArray(arr1);
break;
}
case 2:
{
SetArray(arr2);
PrintArray(arr2);
Spiral(arr2, arr1);
PrintArray(arr1);
break;
}
}
Console.WriteLine();
Console.WriteLine();
} while (choice != 5);
}
static void Diagonal(int[,] array2, int[] array1)
{
int k = 0;
int row = 0;
int col = 0;
while (k < array1.Length)
{
array1[k] = array2[row, col];
if ((row + col) % 2 == 0)
{
if ((row == 0) && (col != array2.GetLength(1) - 1)) { col++; }
else
{
if (col == array2.GetLength(1) - 1) { row++; }
else { row--; col++; }
}
}
else
{
if ((col == 0) && (row != array2.GetLength(0) - 1)) { row++; }
else
{
if (row == array2.GetLength(0) - 1) { col++; }
else { row++; col--; }
}
}
k += 1;
}
}
private static void Spiral(int[,] array2, int[] array1)
{
int lengthX = array2.GetLength(0);
int lengthY = array2.GetLength(1);
int Product = lengthX * lengthY;
int CorrectY = 0;
int CorrectX = 0;
int Count = 0;
while (lengthX > 0 && lengthY > 0)
{
for (int j = CorrectY; j < lengthY && Count < Product; j++)
{
array1[Count] = array2[CorrectX, j];
Count++ ;
}
CorrectX++;
for (int i = CorrectX; i < lengthX && Count < Product; i++)
{
array1[Count] = array2[i, lengthY - 1];
Count++ ;
}
if (lengthY > 0 && lengthX > 0) lengthY-- ;
else break;
for (int j = lengthY - 1; j >= CorrectY && Count < Product; j--)
{
array1[Count] = array2[lengthX - 1, j];
Count++ ;
}
if (lengthY > 0 && lengthX > 0) lengthX-- ;
else break;
for (int i = lengthX - 1; i >= CorrectX && Count < Product; i--)
{
array1[Count] = array2[i, CorrectY];
Count++ ;
}
CorrectY++;
}
}
public static void SetArray(int[,] arr)
{
Random r = new Random();
for (int i = 0; i < arr.GetLength(0); i++)
{
for (int j = 0; j < arr.GetLength(1); j++)
{
arr[i, j] = r.Next(11, 99);
}
}
}
public static void SetArray(int[] arr)
{
Random r = new Random();
for (int i = 0; i < arr.Length; i++)
{
arr[i] = r.Next(11, 99);
}
}
public static void PrintArray(int[] arr)
{
Console.Write("print 1d array:");
for (int i = 0; i < arr.Length; i++)
{
Console.Write(arr[i] + " ");
}
Console.WriteLine();
}
public static void PrintArray(int[,] arr)
{
Console.WriteLine("print 2d array:");
for (int i = 0; i < arr.GetLength(0); i++)
{
for (int j = 0; j < arr.GetLength(1); j++)
{
Console.Write(arr[i, j] + " ");
}
Console.WriteLine();
}
}
}
}
Actually what you are asking is quite easy. Just change your algorithm methods to receive int rows, int cols and delegate like this
delegate void Apply(int row, int col, int index);
Then replace arr2.GetLength(0) with rows, arr2.GetLength(1) with cols, and array element assignments with delegate call.
Here is the updated Diagonal method (you can do the same with the other):
static void Diagonal(int rows, int cols, Apply action)
{
int k = 0;
int row = 0;
int col = 0;
int length = rows * cols;
while (k < length)
{
action(row, col, k);
if ((row + col) % 2 == 0)
{
if ((row == 0) && (col != cols - 1)) { col++; }
else
{
if (col == cols - 1) { row++; }
else { row--; col++; }
}
}
else
{
if ((col == 0) && (row != rows - 1)) { row++; }
else
{
if (row == rows - 1) { col++; }
else { row++; col--; }
}
}
k += 1;
}
}
and the usage:
SetArray(arr2);
PrintArray(arr2);
Diagonal(n, m, (r, c, i) => arr1[i] = arr2[r, c]);
PrintArray(arr1);
// Inverse
var arr3 = new int[n, m];
Diagonal(n, m, (r, c, i) => arr3[r, c] = arr1[i]);
PrintArray(arr3);
This seems to be working for me for backward Diagonal:
static void BackwardDiagonal(int[,] array2, int[] array1) {
int k = 0;
int row = 0;
int col = 0;
while (k < array1.Length) {
array2[row, col] = array1[k]; // just swap sides of the assignment...
if ((row + col) % 2 == 0) {
if ((row == 0) && (col != array2.GetLength(1) - 1)) { col++; } else {
if (col == array2.GetLength(1) - 1) { row++; } else { row--; col++; }
}
} else {
if ((col == 0) && (row != array2.GetLength(0) - 1)) { row++; } else {
if (row == array2.GetLength(0) - 1) { col++; } else { row++; col--; }
}
}
k += 1;
}
}
For backward Spiral:
private static void BackwardSpiral(int[,] array2, int[] array1)
{
int lengthX = array2.GetLength(0);
int lengthY = array2.GetLength(1);
int Product = lengthX * lengthY;
int CorrectY = 0;
int CorrectX = 0;
int Count = 0;
while (lengthX > 0 && lengthY > 0)
{
for (int j = CorrectY; j < lengthY && Count < Product; j++)
{
array2[CorrectX, j] = array1[Count]; // just swap sides of the assignment...
Count++ ;
}
CorrectX++;
for (int i = CorrectX; i < lengthX && Count < Product; i++)
{
array2[i, lengthY - 1] = array1[Count];
Count++ ;
}
if (lengthY > 0 && lengthX > 0) lengthY-- ;
else break;
for (int j = lengthY - 1; j >= CorrectY && Count < Product; j--)
{
array2[lengthX - 1, j] = array1[Count];
Count++ ;
}
if (lengthY > 0 && lengthX > 0) lengthX-- ;
else break;
for (int i = lengthX - 1; i >= CorrectX && Count < Product; i--)
{
array2[i, CorrectY] = array1[Count];
Count++ ;
}
CorrectY++;
}
}
I also added this to the switch statement to implement it:
case 4:
{
SetArray(arr2);
PrintArray(arr2);
Diagonal(arr2, arr1);
PrintArray(arr1);
int[,] arr3 = new int[n, m]; // new blank array to fill with arr1
BackwardDiagonal(arr3, arr1); // fill arr3 from backward Diagonal algorithm
PrintArray(arr3);
break;
}
case 5:
{
SetArray(arr2);
PrintArray(arr2);
Spiral(arr2, arr1);
PrintArray(arr1);
int[,] arr3 = new int[n, m]; // new blank array to fill with arr1
BackwardSpiral(arr3, arr1); // fill arr3 from backward Spiral algorithm
PrintArray(arr3);
break;
}
While you're at it, also make sure to have } while (choice != 3); at the end of your do loop so that you can exit the program!

Simple bubble sort c#

int[] arr = {800,11,50,771,649,770,240, 9};
int temp = 0;
for (int write = 0; write < arr.Length; write++)
{
for (int sort = 0; sort < arr.Length - 1; sort++)
{
if (arr[sort] > arr[sort + 1])
{
temp = arr[sort + 1];
arr[sort + 1] = arr[sort];
arr[sort] = temp;
}
}
Console.Write("{0} ", arr[write]);
}
All I am attempting to do is a simple bubble sort with this array. I would like to figure out why the sorting is screwed up.
In example, here is when the array is {800,11,50,771,649,770,240, 9}:
Here is what gets displayed: 11, 50, 649, 9, 649, 770, 771, 800
I am thinking that I might be missing something in the comparison.
No, your algorithm works but your Write operation is misplaced within the outer loop.
int[] arr = { 800, 11, 50, 771, 649, 770, 240, 9 };
int temp = 0;
for (int write = 0; write < arr.Length; write++) {
for (int sort = 0; sort < arr.Length - 1; sort++) {
if (arr[sort] > arr[sort + 1]) {
temp = arr[sort + 1];
arr[sort + 1] = arr[sort];
arr[sort] = temp;
}
}
}
for (int i = 0; i < arr.Length; i++)
Console.Write(arr[i] + " ");
Console.ReadKey();
This one works for me
public static int[] SortArray(int[] array)
{
int length = array.Length;
int temp = array[0];
for (int i = 0; i < length; i++)
{
for (int j = i+1; j < length; j++)
{
if (array[i] > array[j])
{
temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
return array;
}
public static void BubbleSort(int[] a)
{
for (int i = 1; i <= a.Length - 1; ++i)
for (int j = 0; j < a.Length - i; ++j)
if (a[j] > a[j + 1])
Swap(ref a[j], ref a[j + 1]);
}
public static void Swap(ref int x, ref int y)
{
int temp = x;
x = y;
y = temp;
}
int[] arr = { 800, 11, 50, 771, 649, 770, 240, 9 };
int temp = 0;
for (int write = 0; write < arr.Length; write++)
{
for (int sort = 0; sort < arr.Length - 1 - write ; sort++)
{
if (arr[sort] > arr[sort + 1])
{
temp = arr[sort + 1];
arr[sort + 1] = arr[sort];
arr[sort] = temp;
}
}
}
for (int i = 0; i < arr.Length; i++) Console.Write(arr[i] + " ");
Console.ReadKey();
I saw someone use this example as part of a job application test. My feedback to him was that it lacks an escape from the outer loop when the array is mostly sorted.
consider what would happen in this case:
int[] arr = {1,2,3,4,5,6,7,8};
here's something that makes more sense:
int[] arr = {1,2,3,4,5,6,7,8};
int temp = 0;
int loopCount=0;
bool doBreak=true;
for (int write = 0; write < arr.Length; write++)
{
doBreak=true;
for (int sort = 0; sort < arr.Length - 1; sort++)
{
if (arr[sort] > arr[sort + 1])
{
temp = arr[sort + 1];
arr[sort + 1] = arr[sort];
arr[sort] = temp;
doBreak=false;
}
loopCount++;
}
if(doBreak){ break; /*early escape*/ }
}
Console.WriteLine(loopCount);
for (int i = 0; i < arr.Length; i++) Console.Write(arr[i] + " ");
public static int[] BubbleSort(int[] arr)
{
int length = arr.Length();
while (length > 0)
{
int newLength = 0;
for (int i = 1; i < length; i++)
{
if (arr[i - 1] > arr[i])
{
Swap(ref arr[i - 1], ref arr[i]);
newLength = i;
}
}
length = newLength;
}
}
public static void Swap(ref int x, ref int y)
{
int temp = y;
y = x;
x = temp;
}
I wanted to add to the accepted answer something different:
Number of iterations can be reduced as well, as below.
int[] arr = { 800, 11, 50, 771, 649, 770, 240, 9 };
int temp = 0;
int arrLength = arr.Length;
for (int write = 0; write < arr.Length - 1; write++, arrLength--)
{
for (int sort = 0; sort < arrLength - 1; sort++)
{
if (arr[sort] > arr[sort + 1])
{
temp = arr[sort + 1];
arr[sort + 1] = arr[sort];
arr[sort] = temp;
}
}
}
foreach (var item in arr)
{
Console.WriteLine(item);
}
Your Console.Write("{0} ", arr[write]); is too early. You're printing the values while the sort is still in progress. For example, you're printing 9 as being index 3 in the array, yet on the very next iteration of the loop the 9 has moved to index 2 and 240 has moved to index 3... yet you're outer loop has moved forward so it prints 649 the second time and 240 never gets printed.
int[] array = new int[10] { 13, 2, 5, 8, 23, 90, 41, 4, 77, 61 };
for (int i = 10; i > 0; i--)
{
for (int j = 0; j < 9; j++)
{
if (array[j] > array[j + 1])
{
int temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}
static bool BubbleSort(ref List<int> myList, int number)
{
if (number == 1)
return true;
for (int i = 0; i < number; i++)
{
if ((i + 1 < number) && (myList[i] > myList[i + 1]))
{
int temp = myList[i];
myList[i] = myList[i + 1];
myList[i + 1] = temp;
}
else
continue;
}
return BubbleSort(ref myList, number - 1);
}
Just another example but with an outter WHILE loop instead of a FOR:
public static void Bubble()
{
int[] data = { 5, 4, 3, 2, 1 };
bool newLoopNeeded = false;
int temp;
int loop = 0;
while (!newLoopNeeded)
{
newLoopNeeded = true;
for (int i = 0; i < data.Length - 1; i++)
{
if (data[i + 1] < data[i])
{
temp = data[i];
data[i] = data[i + 1];
data[i + 1] = temp;
newLoopNeeded = false;
}
loop++;
}
}
}
Bubble sort with sort direction -
using System;
public class Program
{
public static void Main(string[] args)
{
var input = new[] { 800, 11, 50, 771, 649, 770, 240, 9 };
BubbleSort(input);
Array.ForEach(input, Console.WriteLine);
Console.ReadKey();
}
public enum Direction
{
Ascending = 0,
Descending
}
public static void BubbleSort(int[] input, Direction direction = Direction.Ascending)
{
bool swapped;
var length = input.Length;
do
{
swapped = false;
for (var index = 0; index < length - 1; index++)
{
var needSwap = direction == Direction.Ascending ? input[index] > input[index + 1] : input[index] < input[index + 1];
if (needSwap)
{
var temp = input[index];
input[index] = input[index + 1];
input[index + 1] = temp;
swapped = true;
}
}
} while (swapped);
}
}
This is what I wrote using recursive methods:
public static int[] BubbleSort(int[] input)
{
bool isSorted = true;
for (int i = 0; i < input.Length; i++)
{
if (i != input.Length - 1 && input[i] > input[i + 1])
{
isSorted = false;
int temp = input[i];
input[i] = input[i + 1];
input[i + 1] = temp;
}
}
return isSorted ? input : BubbleSort(input);
}
It does the same in a more elegant way.
var arrayValues = new[] { 99, 12, 11, 300, 400, 10, 9, 3, 6, 5, 7, 8};
for (var mainLoop = 0; mainLoop < arrayValues.Length; mainLoop++)
{
for (var innerLoop = mainLoop + 1; innerLoop < arrayValues.Length; innerLoop++)
{
if (arrayValues[mainLoop] <= arrayValues[innerLoop])
{
continue;
}
var temp = arrayValues[mainLoop];
arrayValues[mainLoop] = arrayValues[innerLoop];
arrayValues[innerLoop] = temp;
}
}
So i did mine as a recursive function (no need for the nested loop), perhaps someone could comment if this is inefficient (when compared to the other solutions).
public static int[] BubbleSort(int[] arrayOfValues)
{
var swapOccurred = false;
for (var i = 0; i < arrayOfValues.Length; i++)
{
if (i == arrayOfValues.Length - 1)
continue;
if (arrayOfValues[i] > arrayOfValues[i + 1])
{
//swap values
var current = arrayOfValues[i];
var next = arrayOfValues[i + 1];
arrayOfValues[i] = next;
arrayOfValues[i + 1] = current;
swapOccurred = true;
}
}
if (swapOccurred)
{
// keep going until no further swaps are required:
BubbleSort(arrayOfValues);
}
return arrayOfValues;
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Practice {
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter the size");
int n = Convert.ToInt32(Console.ReadLine());
int[] mynum = new int[n];
Console.WriteLine("Enter the Numbers");
for (int p = 0; p < n;p++ )
{
mynum[p] = Convert.ToInt32(Console.ReadLine());
}
Console.WriteLine("The number are");
foreach(int p in mynum)
{
Console.WriteLine(p);
}
for (int i = 0; i < n;i++ )
{
for(int j=i+1;j<n;j++)
{
if(mynum[i]>mynum[j])
{
int x = mynum[j];
mynum[j] = mynum[i];
mynum[i] = x;
}
}
}
Console.WriteLine("Sortrd data is-");
foreach(int p in mynum)
{
Console.WriteLine(p);
}
Console.ReadLine();
}
} }
int[] arr = { 800, 11, 50, 771, 649, 770, 240, 9 };
for (int i = 0; i < arr.Length; i++)
{
for (int j = i; j < arr.Length ; j++)
{
if (arr[j] < arr[i])
{
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
Console.ReadLine();
public void BubbleSortNum()
{
int[] a = {10,5,30,25,40,20};
int length = a.Length;
int temp = 0;
for (int i = 0; i <length; i++)
{
for(int j=i;j<length; j++)
{
if (a[i]>a[j])
{
temp = a[j];
a[j] = a[i];
a[i] = temp;
}
}
Console.WriteLine(a[i]);
}
}

Categories

Resources