How do I set the debugger to catch what changed the variable - c#

I am implementing the NEH algorithm following this slide and video:
http://mams.rmit.edu.au/b5oatq61pmjl.pdf
https://www.youtube.com/watch?v=TcBzEyCQBxw
My problem during the test is the variable Sorted_list got changed which cause different results from what I expect:
This the portion where I have the problem but I couldn't know what it changes it(I used breakpoints and watch variable window):
for (int i = 0; i < kmsList.Count; i++)
{
for (int j = 0; j < kmsList[i].Length - 1; j++)
{
/*
*
* HERE Sorted_list GET MODIFIED UNEXPECTEDLY
*/
if (i == 0 && j == 0)
kmsList[0][0] = Sorted_list[0][0];
else if (i == 0)
kmsList[0][j] = kmsList[0][j - 1] + Sorted_list[0][j];
else if (j == 0)
kmsList[i][0] = kmsList[i - 1][0] + Sorted_list[i][0];
}
}
Complete implementation:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FINAL_NEH
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("entre the nmbr of jobs : ");
string row = Console.ReadLine();
Console.WriteLine("entre the nmbr of machines : ");
string column = Console.ReadLine();
int job = int.Parse(row.ToString());
int machine = int.Parse(column.ToString());
List<int[]> list = new List<int[]>();
// read the nmbrs and put it in list-----------------------------------------------------
for (int i = 0; i < job; i++)
{
list.Add(new int[machine + 1]);
for (int j = 0; j < machine; j++)
{
list[i][j] = int.Parse(Console.ReadLine());
}
list[i][list[i].Length - 1] = int.Parse((i + 1).ToString()); //Last Elemnt Is Job Number-
}
// show the list----------------------------------------------------------------------------
for (int i = 0; i < job; i++)
{
for (int j = 0; j < machine + 1; j++)
{
Console.Write("\t" + "[" + list[i][j] + "]");
}
Console.WriteLine();
}
// sort the list------------------------------------------------------------------------------
for (int i = 0; i < list.Count; i++)
{
for (int j = i + 1; j < list.Count; j++)
{
int sumI = 0, sumJ = 0;
for (int a = 0; a < list[i].Length - 1; a++)
{
sumI += list[i][a];
}
for (int a = 0; a < list[j].Length - 1; a++)
{
sumJ += list[j][a];
}
if (sumI < sumJ)
{
int[] temp = new int[int.Parse(job.ToString())];
temp = list[i];
list[i] = list[j];
list[j] = temp;
}
}
}
Console.Write("\n\n-----------------after sorting ------------------------------------\n\n");
// shaw the list after sorting------------------------------------------
for (int i = 0; i < job; i++)
{
for (int j = 0; j < machine + 1; j++)
{
Console.Write("\t" + "[" + list[i][j] + "]");
}
Console.WriteLine();
}
// clculate the maxpane of the first 2 jobs---------------------------------------
List<int[]> initMaxpane = new List<int[]>();
initMaxpane.Add((int[])list[0].Clone());
initMaxpane.Add((int[])list[1].Clone());
// calculer maxspan of first jobs..............................................
for (int i = 0; i < initMaxpane.Count; i++)
{
for (int j = 0; j < initMaxpane[i].Length - 1; j++)
{
if (j == 0 && i == 0)
initMaxpane[0][0] = list[i][j];
else if (i == 0)
initMaxpane[0][j] = (int)(initMaxpane[0][j - 1] + list[0][j]);
else if (j == 0)
initMaxpane[i][0] = (int)(initMaxpane[i - 1][0] + list[i][0]);
}
}
for (int i = 1; i < initMaxpane.Count; i++)
{
for (int j = 1; j < initMaxpane[i].Length - 1; j++)
{
if ((initMaxpane[i][j - 1] > initMaxpane[i - 1][j]))
initMaxpane[i][j] = (int)(initMaxpane[i][j - 1] + list[i][j]);
else
initMaxpane[i][j] = (int)(initMaxpane[i - 1][j] + list[i][j]);
}
}
int Cmax = initMaxpane[initMaxpane.Count - 1][initMaxpane[initMaxpane.Count - 1].Length - 2];
Console.WriteLine("\n\n-------the maxpane offirst jobs----------");
for (int i = 0; i < initMaxpane.Count; i++)
{
for (int j = 0; j < initMaxpane[i].Length; j++)
{
Console.Write("\t" + "[" + initMaxpane[i][j] + "]");
}
Console.WriteLine();
}
List<int[]> initMaxpane2 = new List<int[]>();
initMaxpane2.Add(list.ElementAt(1));
initMaxpane2.Add(list.ElementAt(0));
// calculer maxspan of first jobs reverse..............................................
for (int i = 0; i < initMaxpane2.Count; i++)
{
for (int j = 0; j < initMaxpane2[i].Length - 1; j++)
{
if (j == 0 && i == 0)
initMaxpane2[0][0] = list[i][j];
else if (i == 0)
initMaxpane2[0][j] = (int)(initMaxpane2[0][j - 1] + list[0][j]);
else if (j == 0)
initMaxpane2[i][0] = (int)(initMaxpane2[i - 1][0] + list[i][0]);
}
}
for (int i = 1; i < initMaxpane2.Count; i++)
{
for (int j = 1; j < initMaxpane2[i].Length - 1; j++)
{
if ((initMaxpane2[i][j - 1] > initMaxpane2[i - 1][j]))
initMaxpane2[i][j] = (int)(initMaxpane2[i][j - 1] + list[i][j]);
else
initMaxpane2[i][j] = (int)(initMaxpane2[i - 1][j] + list[i][j]);
}
}
int Cmax2 = initMaxpane2[initMaxpane2.Count - 1][initMaxpane2[initMaxpane2.Count - 1].Length - 2];
Console.WriteLine("\n\n-------the maxpane of first jobs (reverse)----------");
for (int i = 0; i < initMaxpane2.Count; i++)
{
for (int j = 0; j < initMaxpane2[i].Length; j++)
{
Console.Write("\t" + "[" + initMaxpane2[i][j] + "]");
}
Console.WriteLine();
}
List<int[]> MaxpaneList = new List<int[]>();
if (Cmax > Cmax2)
{
MaxpaneList.Add((int[])list[1].Clone());
MaxpaneList.Add((int[])list[0].Clone());
}
else
{
MaxpaneList.Add((int[])list[0].Clone());
MaxpaneList.Add((int[])list[1].Clone());
}
List<int[]> bestSequenceList = null;
List<int[]> kmsList = null;
List<int[]> Sorted_list = list.ToList();
int bestCma = 0;
//int maxspan = 0;
for (int jo = 2; jo < job; jo++)
{
for (int ins = 0; ins <= MaxpaneList.Count; ins++)
{
MaxpaneList.Insert(ins, list[jo]);
kmsList = MaxpaneList.ToList();
int Cma = 0;
for (int i = 0; i < kmsList.Count; i++)
{
for (int j = 0; j < kmsList[i].Length - 1; j++)
{
/*
*
* HERE Sorted_list GET MODIFIED UNEXPECTEDLY
*/
if (i == 0 && j == 0)
kmsList[0][0] = Sorted_list[0][0];
else if (i == 0)
kmsList[0][j] = kmsList[0][j - 1] + Sorted_list[0][j];
else if (j == 0)
kmsList[i][0] = kmsList[i - 1][0] + Sorted_list[i][0];
}
}
for (int i = 1; i < kmsList.Count; i++)
{
for (int j = 1; j < kmsList[i].Length - 1; j++)
{
if ((kmsList[i][j - 1] > kmsList[i - 1][j]))
kmsList[i][j] = kmsList[i][j - 1] + Sorted_list[i][j];
else
kmsList[i][j] = kmsList[i - 1][j] + Sorted_list[i][j];
}
}
Cma = kmsList[kmsList.Count - 1][kmsList[kmsList.Count - 1].Length - 2];
Console.WriteLine("\n\n\n------- the maxpane sequence ----------");
for (int i = 0; i < MaxpaneList.Count; i++)
{
for (int j = 0; j < MaxpaneList[i].Length; j++)
{
Console.Write("\t" + "[" + MaxpaneList[i][j] + "]");
}
Console.WriteLine();
}
Console.WriteLine("MAX : " + Cma + "\n\n\n");
if (ins == 0)
{
bestCma = Cma;
}
if (jo == 2 && ins == 0)
{
bestSequenceList = MaxpaneList.ToList();
bestCma = Cma;
}
else
{
if (bestCma > Cma)
{
bestSequenceList = MaxpaneList.ToList();
bestCma = Cma;
}
}
MaxpaneList.RemoveAt(ins);
}
MaxpaneList = bestSequenceList.ToList();
}
Console.ReadLine();
}
}
}

The issue lies in the following code (snippet):
List<int[]> Sorted_list = list.ToList();
ToList will create a new list, but because in this case int[] is a reference type then the new list will contain references to the same arrays as the original list.
Updating a value (of an array) referenced in the new list will also affect the equivalent value in the original list.
kmsList[0][0] = Sorted_list[0][0];
The solution is to create a real copy of 'list' and its items (in this case int[]):
List<int[]> Sorted_list = list.ConvertAll(myArray => (int[])myArray.Clone());
This piece of code clones all arrays within the list to a new variable Sorted_list.
A useful link that explains the difference between value and reference types is: https://msdn.microsoft.com/en-us/library/t63sy5hs.aspx
Reference Types
A reference type contains a pointer to another memory location that holds the data.
Reference types include the following:
String
All arrays, even if their elements are value types Class
types, such as Form
Delegates

When you create a List<> (or any other container) from another container (as you do when you call list.ToList()) you do not create copies of all of the elements in the container. You create new references to the items in the list that you're copying. In CS parlance it's a shallow copy and not a deep copy.
So, if you do this:
int[] ia = new[] {0, 1, 2, 3, 4};
int[] ib = new[] {5, 6, 7, 8, 9};
List<int[]> la = new List<int[]>() { ia, ib };
List<int[]> lb = la.ToList();
Both lists refer to the same two arrays, and if you change one array like this:
la[1][4] = 10;
Then lb[1][4] will also be 10 because the two lists each contain the same arrays. Copying the list does not copy the elements in the list.

Related

element swapping in a 4x4 array with numbers

I am making a game like this one : https://i.stack.imgur.com/mnbFw.jpg. I am having trouble coding the algorithm to swap numbers between each others. In my game , the 0 acts as the empty tile. This algorithm was originally for a 3x3 grid but I simply switched the 3's to 4's. I think that this is what's causing issues but I can't seem to find why.
{
int j, i;
for (i = 1; i < 4; i++)
{
for (j = 0; j < 4; j++)
{
if (t1[i, j] == 0)
{
t1[i, j] = t1[i - 1, j];
t1[i - 1, j] = 0;
}
}
}
}
static void scan_above(int[,] t1)
{
int j, i;
for (i = 1; i >= 0; i--)
{
for (j = 0; j < 4; j++)
{
if (t1[i, j] == 0)
{
t1[i, j] = t1[i + 1, j];
t1[i + 1, j] = 0;
}
}
}
}
static void scan_left(int[,] t1)
{
int j, i;
for (j = 1; j >= 0; j--)
{
for (i = 0; i < 4; i++)
{
if (t1[i, j] == 0)
{
t1[i, j] = t1[i, j + 1];
t1[i, j + 1] = 0;
}
}
}
}
static void scan_right(int[,] t1)
{
int j, i;
for (j = 1; j < 4; j++)
{
for (i = 0; i < 4; i++)
{
if (t1[i, j] == 0)
{
t1[i, j] = t1[i, j - 1];
t1[i, j - 1] = 0;
}
}
}
}```
I'm confused about why you're looping through all the values in the matrix. Unless there are considerations that aren't included in the question, this is all it should take:
static void MoveRight(int xOfZero, int yOfZero)
{
int rightValue = spaces[xOfZero, yOfZero + 1];
spaces[xOfZero, yOfZero + 1] = 0;
spaces[xOfZero, yOfZero] = rightValue;
}
FYI I hastily put together my matrix so it's indexed backwards, where x is the row number and y is the column. You could easily follow the same steps to make a move for every direction.

Can't perambulate indexes in matrix the right way

Hello. I have this task to sum the numbers as shown. Tried everything I can, but still not the right answer. Can I have some guidance?
static void Main(string[] args)
{
string input = Console.ReadLine();
int n = (int)char.GetNumericValue(input[0]);
int m = (int)char.GetNumericValue(input[2]);
int[,] matrix = new int[n, m];
int sum = 0;
//fill matrix
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
matrix[i, j] = (j * 3 + 1) + i * 3;
}
}
for (int i = 0; i < matrix.GetLength(0) - 1; i+=1)
{
for (int j = 0; j < matrix.GetLength(1) - i; j+=1)
{
if (i % 2 == 0)
{
sum += matrix[i, j + i] + matrix[i + 1, j + 1];
}
}
}
Console.WriteLine(sum);
}
I think you would've a easier time hard coding the input (and naming them as "columns" and "rows" instead, much more readable).
What is the expected output? Not sure I'm following this sum. I'm guessing, 297? If so:
for (int i = 0; i < matrix.GetLength(0); i++)
{
for (int j = 0; j < matrix.GetLength(1); j++)
{
Console.Write(matrix[i, j] + " ");
if(j == 5) Console.WriteLine();
if (matrix[i, j] % 2 != 0)
{
if (i == 0 || i == matrix.GetLength(0) - 1
|| j == 0 || j == matrix.GetLength(0))
{
sum += (matrix[i, j]);
}
else
{
sum += (matrix[i, j] * 2);
}
}
}
}

C# [i, j] add the min "j" values ​of matrix to the new array?

[i, j] add the biggest values ​​of matrix to j the new array
its here:
But smallest not working..
Min values in "j" (not working)
for (int i = 0; i < olay; i++)
{
for (int j = 0; j < state; j++)
{
if (minimax[i] > matris[i, j])
{
minimax[i] = matris[i, j];
}
}
}
Console.WriteLine();
for (int i = 0; i < minimax.Length; i++)
{
Console.WriteLine(i + 1 + ". MINIMAX " + minimax[i]);
}
Console.ReadLine();
}
Max VALUES IN "J" (WORKING)
for (int i = 0; i < olay; i++)
{
for (int j = 0; j < state; j++)
{
if (maximax[i] < matris[i, j])
{
maximax[i] = matris[i, j];
}
}
}
/* Olaylar icin en yuksek State degerleri */
Console.WriteLine();
for (int i = 0; i < maximax.Length; i++)
{
Console.WriteLine(i + 1 + ". MAXIMAX " + maximax[i]);
}
Output console:
IMG Lınk: https://pasteboard.co/IKKQlet.jpg
The default values in your arrays are 0.
To calculate the minimum value in each column and write it to an array you can do something like this:
var resultArray = new int[rowLength];
var matrix = new int[rowLength, columnLength];
for (int i = 0; i < rowLength; i++)
{
// you have to set the first value as a minimum and after that compare
resultArray[i] = matrix[i, 0];
for (int j = 1; j < columnLength; j++)
{
if (matrix[i, j] < resultArray[i])
{
resultArray[i] = matrix[i, j];
}
}
}

How should weights be optimized with gradient descent algorithm in order to work?

I have a neural network in visual studio. for the loss function I am using a basic cost function (pred-target)**2 and after I finish an epoch I optimize the parameter functions afterwards, but the algorithm doesn't work.
No matter what is my network configuration, the predictions are not write (it is the same output for all the inputs) and the loss function is not optimized. It stays the same through all the epochs.
void calc_lyr(int x, int y, int idx, float target) // thus function calculates the neuron value based on the previous layer
{
if (x == -1 || y == 0) // if its the first layer, get the data from input nodes
{
for (int i = 0; i < neurons[y]; i++)
{
float sum = 0;
for (int j = 0; j < inputTypes.Count; j++)
{
sum += weights[x+1][j][i] * training_test[idx][j];
}
sum = relu(sum);
vals[y+1][i] = sum;
}
}
else
{
for(int i = 0; i < neurons[y]; i++)
{
float sum = 0;
for(int j = 0; j < neurons[x]; j++)
{
sum += weights[x+1][j][i] * vals[x+1][j] + biases[y][i];
}
sum = relu(sum);
vals[y+1][i] = sum;
}
}
}
void train()
{
log("Proces de antrenare inceput ----------------- " + DateTime.Now.ToString());
vals = new List<List<float>>();
weights = new List<List<List<float>>>();
biases = new List<List<float>>();
Random randB = new Random(DateTime.Now.Millisecond);
Random randW = new Random(DateTime.Now.Millisecond);
for (int i = 0; i <= nrLayers; i++)
{
progressEpochs.Value =(int)(((float)i * (float)nrLayers) / 100.0f);
vals.Add(new List<float>());
weights.Add(new List<List<float>>());
if (i == 0)
{
for (int j = 0; j < inputTypes.Count; j++)
{
vals[i].Add(0);
}
}
else
{
biases.Add(new List<float>());
for (int j = 0; j < neurons[i-1]; j++)
{
vals[i].Add(0);
float valB = (float)randB.NextDouble();
biases[i-1].Add(valB - ((int)valB));
}
}
}
float valLB = (float)randB.NextDouble();
biases.Add(new List<float>());
biases[nrLayers].Add(valLB - ((int)valLB));
for (int i = 0; i <= nrLayers; i++)
{
if (i == 0)
{
for (int j = 0; j < inputTypes.Count; j++)
{
weights[i].Add(new List<float>());
for (int x = 0; x < neurons[i]; x++)
{
float valW = (float)randW.NextDouble();
weights[i][j].Add(valW);
}
}
}
else if (i == nrLayers)
{
for (int j = 0; j < neurons[i-1]; j++) {
weights[i].Add(new List<float>());
weights[i][j].Add(0);
}
}
else
{
for (int j = 0; j < neurons[i - 1]; j++)
{
weights[i].Add(new List<float>());
for (int x = 0; x < neurons[i]; x++)
{
float valW = (float)randW.NextDouble();
weights[i][j].Add(valW);
}
}
}
}
Random rand = new Random(DateTime.Now.Millisecond);
log("\n\n");
for (int i = 0; i < epochs; i++)
{
log("Epoch " + (i + 1).ToString() + " inceput ---> " + DateTime.Now.ToString());
int idx = rand.Next() % training_test.Count;
float target = outputsPossible.IndexOf(training_labels[idx]);
for (int j = 0; j < nrLayers; j++)
{
calc_lyr(j - 1, j, idx, target);
}
float total_val = 0;
for(int x = 0; x < neurons[nrLayers - 1]; x++)
{
float val = relu(weights[nrLayers][x][0] * vals[nrLayers][x] + biases[nrLayers][0]);
total_val += val;
}
total_val = sigmoid(total_val);
float cost_res = cost(total_val, target);
log("Epoch " + (i+1).ToString() + " terminat ----- " + DateTime.Now.ToString() + "\n");
log("Eroare epoch ---> " + (cost_res<1?"0":"") + cost_res.ToString("##.##") + "\n\n\n");
float cost_der = cost_d(total_val, target);
for (int a = 0; a < weights.Count; a++)
{
for (int b = 0; b < weights[a].Count; b++)
{
for (int c = 0; c < weights[a][b].Count; c++)
{
weights[a][b][c]-=cost_der*learning_rate * sigmoid_d(weights[a][b][c]);
}
}
}
for (int a = 0; a < nrLayers; a++)
{
for (int b = 0; b < neurons[a]; b++)
{
biases[a][b] -= cost_der * learning_rate;
}
}
}
hasTrained = true;
testBut.Enabled = hasTrained;
MessageBox.Show("Antrenament complet!");
SavePrompt sp = new SavePrompt();
sp.Show();
}
How can it be changed to optimize the weights, biases and loss function? For now, when I try to debug, the weights are changing, but it is the same value for the loss function.
I solved it by using AForge.NET: link

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