Bubble sorting issues - c#

Im currently writing code to sort an array through bubble sort. I've previously written it using a set array that i created and it worked perfectly. However, i tried to change it to a randomly generated array and its now broken. wondered if anyone could give me a hand. thanks in advance.
using System;
namespace BubbleSot_Fin
{
class Program
{
static void Main(string[] args)
{
int N = 5;
int m = 100;
int i = 1; //n = number of values m = max value in array
Random Rand = new Random();
int[] array = new int[N + 1];
for ( i = 1; i <= N; i++)
{
array[i] = Rand.Next(1, m); //Randomise the array
Console.WriteLine("This is the unsorted array");
Console.WriteLine("");
for (i = 0; i < array.Length; i++)
{
Console.WriteLine("A[" + i + "] = " + array[i] ); // shows the unsorted numbers
}
int[] Bubble = BubbleSort(array);
Console.WriteLine("");
Console.WriteLine("Array after Bubble Sort");
Console.WriteLine("");
for ( i = 0; i < Bubble.Length; i++)
{
Console.WriteLine("A[" + i + "] = " + Bubble[i]); // shows the numbers after sorting
}
Console.ReadLine();
}
private static int[] BubbleSort(int[] BSArray)
{
int length = array.Length;
for ( i = 0; i < length - 1; i++)
{
for (int j = 0; j < length - 1 - i; j++)
{
if (array[j] > array[j + 1])
{
int number = array[j];
array[j] = array[j + 1];
array[j + 1] = number;
}
}
}
return BSArray;
}
}
}
The errors i'm having are that the private and static word for the bubble sort are incorrect.
The errors are :
- CS0106 The modifier 'Private' is not valid for this item
- CS0106 The modifier 'Static' is not valid for this item

Related

Is there a way to throw an exception when string is typed in an arrayc#?

I am new in this fascinating world of programming. I have done this array, but when I type a non integer it crashes. I have tried many ways like int.Parse(console.readLine)), tryparse(text, out int) and ConvertTo32 ,However it continues saying that "Input string was not in correct format." Thanks
using System;
namespace BubbleSort
{
class Program
{
public static void HelpME(int[] a, int t)
{
for (int j = 0; j <= a.Length - 2; j++)
{
for (int i = 0; i <= a.Length - 2; i++)
{
if (a[i] > a[i + 1])
{
t = a[i + 1];
a[i + 1] = a[i];
a[i] = t;
}
}
}
}
static void Main(string[] args)
{
int[] num = { 1, 2, 3, 4, 5 };
int[] a = new int[5];
for (int x = 0; x < 5; x++)
{
Console.WriteLine($"Input enter {num[0 + x]} of five");
a[0 + x] = Convert.ToInt32(Console.ReadLine());
}
Console.WriteLine("The Array is : ");
for (int i = 0; i < a.Length; i++)
{
Console.WriteLine(a[i]);
}
{
HelpME(num, 5);
}
Console.WriteLine("The Sorted Array :");
foreach (int aray in a)
{
Console.Write(aray + " ");
}
Console.ReadLine();
}
}
}
you should validate the user unput by using int.TryParse method. If the entered string can be converted to int then only it should be inserted into the array, otherwise the program should ignore that value.
static void Main(string[] args)
{
int[] num = { 1, 2, 3, 4, 5 };
int[] a = new int[5];
for (int x = 0; x < 5; x++)
{
Console.WriteLine($"Input enter {num[0 + x]} of five");
int temp = 0;
string input = Console.ReadLine();
if(int.TryParse(input, out temp))
{
a[0 + x] = Convert.ToInt32(input);
}
}
Console.WriteLine("The Array is : ");
for (int i = 0; i < a.Length; i++)
{
Console.WriteLine(a[i]);
}
{
HelpME(num, 5);
}
Console.WriteLine("The Sorted Array :");
foreach (int aray in a)
{
Console.Write(aray + " ");
}
Console.ReadLine();
}

Count the number of occurrences in an array with random numbers without methods or list in C#

I am trying to solve an exercise in C# as follows:
Write a program that generates 20 random integers between 0 and 9 and displays the count for each number.
Use an array of ten integers, say counts, to store the counts for the number of 0s, 1s, ..., 9s.)
This is what i come up with which kind of work but i have a problem with the 0's counting 1 extra all the time.
using System.Collections.Generic;
using System.Text;
namespace ArrayExercises
{
class TaskFive
{
public static void FindNumberCount()
{
int c0=0,c1=02,c2=0,c3=0,c4=0,c5=0,c6=0,c7=0,c8=0,c9=0;
int[] arr = new int[20];
Random rand = new Random();
Console.WriteLine("Numbers generated ");
for (int i = 0; i < 19; i++)
{
arr[i] = rand.Next(0, 10);
Console.WriteLine(arr[i]);
}
foreach(int number in arr)
{
if (number == 0) { c0++; }
else if (number == 1) { c1++; }
else if (number == 2) { c2++; }
else if (number == 3) { c3++; }
else if (number == 4) { c4++; }
else if (number == 5) { c5++; }
else if (number == 6) { c6++; }
else if (number == 7) { c7++; }
else if (number == 8) { c8++; }
else if (number == 9) { c9++; }
}
Console.WriteLine
(
$"Number of 0's: {c0} \n" +
$"Number of 1's: {c1} \n" +
$"Number of 2's: {c2} \n" +
$"Number of 3's: {c3} \n" +
$"Number of 4's: {c4} \n" +
$"Number of 5's: {c5} \n" +
$"Number of 6's: {c6} \n" +
$"Number of 7's: {c7} \n" +
$"Number of 8's: {c8} \n" +
$"Number of 9's: {c9}"
);
}
}
}
Thanks in advance :)
You could shorten it like this
public static void FindNumberCount()
{
int[] count = new int[10];
Random rand = new Random();
int[] arr = new int[20];
for (int i = 0; i < arr.Length; i++)
{
arr[i] = rand.Next(0, 10);
Console.WriteLine(arr[i]);
count[arr[i]]++;
}
for (int i = 0; i < count.Length; i++)
{
Console.WriteLine($"Number of {i}'s: {count[i]}");
}
}
If you want draw 20 numbers you should for (int i = 0; i < 20; i++) not 19.
int[] counts = new int[10];
int[] numbers = new int[20];
var random = new Random();
for (int i = 0; i < numbers.Length; i++)
{
// Generate random numbers
numbers[i] = random.Next(0, 9);
// Increment the count of the generated number
counts[numbers[i]]++;
}
the for loop you use loops only 19 times.
You must change the "i < 19" to "i < 20".
In your program, the for loop leaves the last int in the array at it's default value (0),
this also explains, why you always have one more zero.
Hope this helped.
The issues is in this line
for (int i = 0; i < 19; i++)
You initialized an array with 20 int and set only value to 19 of them.
If you don't set the value int defaults to Zero and hence you always get one extra zero
Change your code as below
for (int i = 0; i <= 19; i++)
The halting condition of the first for loop should be i<20. Then your program should work.
This is how I would solve it:
static void Main(string[] args)
{
Random random = new Random();
//Fill array with random numbers
int[] array = new int[20];
for (int i = 0; i < array.Length; i++)
array[i] = random.Next(0, 10);
//Count how many times a number occurs
int[] numberCounts = new int[10];
for (int i = 0; i < array.Length; i++)
numberCounts[array[i]]++;
//Print the count of the numbers
for(int i = 0; i < numberCounts.Length; i++)
Console.WriteLine("Number of " + i + "'s: " + numberCounts[i]);
//Keep the console open
Console.ReadLine();
}

How to fix this implementaion of the Merge Sort in c#

I've read the CLRS and tried to implement the recursive merge sort algorithm . cant see what the error is but everytime i run it gives me an "Index out of bounds error "
i've been trying for 5h now
static public void MergeSort(int[] input, int IndexStanga, int IndexDreapta)
{
if (IndexStanga < IndexDreapta)
{
int IndexMijloc = (IndexDreapta + IndexStanga) / 2;
MergeSort(input, IndexStanga, IndexMijloc);
MergeSort(input, IndexMijloc + 1, IndexDreapta);
Merge(input, IndexStanga, IndexDreapta, IndexMijloc);
}
}
static public void Merge(int[] input, int stanga, int dreapta, int mijloc)
{
int lungDR = 0;
int lunST = 0;
lungDR = dreapta - mijloc;
lunST = mijloc - stanga + 1;
int[] valDreapta = new int[lungDR + 1];
int[] valStanga = new int[lunST + 1];
valDreapta[valDreapta.Length - 1] = int.MaxValue;
valStanga[valStanga.Length - 1] = int.MaxValue;
int i = 0;
int j = 0;
for (i = stanga; i <= mijloc; i++) valStanga[i] = input[i];
for (i = 0; i < lungDR; i++) { valDreapta[i] = input[i + mijloc + 1]; }
i = 0;
j = 0;
for (int k = 0; k < input.Length; k++)
{
if (valStanga[i] <= valDreapta[j]) //error out of bounds
{
input[k] = valStanga[i];
i++;
}
else
{
input[k] = valDreapta[j];
j++;
}
}
}
Fixes noted in comments below. First fix for moving data from input to valStanga. Second fix for the range on merging back to input. The parameters for merge are in an unusual order, first, last, middle. Normally the order is first, middle, last.
Comments: The program will have issues if the array to be sorted contains elements equal to max integer. It would be more efficient to do a one time allocation of a working array, rather than allocate new sub-arrays on every call to merge. The copy operations can be avoided by changing the direction of merge with each level of recursion.
int i = 0;
int j = 0;
for (i = 0; i < lungDR; i++) { valDreapta[i] = input[i + mijloc + 1]; }
for (i = 0; i < lunST; i++) { valStanga[i] = input[i + stanga]; } // fix
i = 0;
j = 0;
for (int k = stanga; k <= dreapta; k++) // fix
{
if (valStanga[i] <= valDreapta[j])

How to find the maximal (longest) sequence of increasing elements in an array arr[n]?

I need to write a program, which finds the maximal sequence of increasing elements in an array arr[n]. It is not necessary the elements to be consecutively placed. E.g.: {9, 6, 2, 7, 4, 7, 6, 5, 8, 4} -> {2, 4, 6, 8}.
I have some guidelines to use 2 nested loops and one additional array.
So far i know how to use if statements, loops and little arrays.
Any suggestions pls...?
This is my start so far (am I on a good track?):
Console.Write("Elements in array: ");
int n = int.Parse(Console.ReadLine());
int[] arr = new int[n];
int[] result;
for (int index = 0; index < arr.Length; index++)
{
Console.Write("Array [{0}] = ", index);
arr[index] = int.Parse(Console.ReadLine());
}
for (int indexOut = 0; indexOut < n; indexOut++)
{
for (int indexIn = 1; indexIn < n; indexIn++)
{
}
}
nested loops are 1 loop inside another:
for (int 1 = 0; i < something.length; i++) {
for ( int j = 0; j < somethingElse.length; j++) {
// code
}
}
I think I found your solution here:
http://www.geeksforgeeks.org/dynamic-programming-set-3-longest-increasing-subsequence/
/* Dynamic Programming C/C++ implementation of LIS problem */
#include<stdio.h>
#include<stdlib.h>
/* lis() returns the length of the longest increasing
subsequence in arr[] of size n */
int lis( int arr[], int n )
{
int *lis, i, j, max = 0;
lis = (int*) malloc ( sizeof( int ) * n );
/* Initialize LIS values for all indexes */
for ( i = 0; i < n; i++ )
lis[i] = 1;
/* Compute optimized LIS values in bottom up manner */
for ( i = 1; i < n; i++ )
for ( j = 0; j < i; j++ )
if ( arr[i] > arr[j] && lis[i] < lis[j] + 1)
lis[i] = lis[j] + 1;
/* Pick maximum of all LIS values */
for ( i = 0; i < n; i++ )
if ( max < lis[i] )
max = lis[i];
/* Free memory to avoid memory leak */
free( lis );
return max;
}
/* Driver program to test above function */
int main()
{
int arr[] = { 10, 22, 9, 33, 21, 50, 41, 60 };
int n = sizeof(arr)/sizeof(arr[0]);
printf("Length of LIS is %d\n", lis( arr, n ) );
return 0;
}
You will have to modify it a little to generate the actual array.
My code:
// Arr[]
int n = 10;
int[] arr = new int[n];
for (int index = 0; index < n; index++)
{
Console.Write("Array[{0}] = ", index);
arr[index] = int.Parse(Console.ReadLine());
}
// Len[]
int[] len = new int[n];
for (int index = 0; index < n; index++)
{
len[index] = 1;
}
// Correct len[]
for (int indexCount = 1; indexCount < n; indexCount++)
{
for (int indexNumber = 0; indexNumber < indexCount; indexNumber++)
{
if (arr[indexCount] > arr[indexNumber] && len[indexCount] < len[indexNumber] + 1)
{
len[indexCount] = len[indexNumber] + 1;
}
}
}
// Print new len[]
// Just to keep track of numbers
Console.WriteLine();
Console.Write("{");
for (int index = 0; index < n; index++)
{
Console.Write(" " + len[index] + " ");
}
Console.WriteLine("}");
// Search for the max number in len[]
int max = int.MinValue;
int maxPosition = 0;
for (int index = 0; index < len.Length; index++)
{
if (len[index] > max)
{
max = len[index];
maxPosition = index;
}
}
// Create the result in result[]
int[] result = new int[max];
int i = (max - 1);
int maxCount = max;
for (int index = maxPosition; index >= 0; index--)
{
if (len[index] == max)
{
result[i] = arr[index];
max--;
i--;
}
}
// Print the result[]
Console.WriteLine();
Console.Write("{");
for (int index = 0; index < maxCount; index++)
{
Console.Write(" " + result[index] + " ");
}
Console.WriteLine("}");
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int maincount = 0;
int indices = 0;
int increment = 0;
int count = 0;
int finalcount = 0;
int checkvalue = 0;
string consincval = null;
string consincval1 = null;
string finalconsincval = null;
Console.WriteLine("Enter number of rows of the array");
int len = int.Parse(Console.ReadLine());
Console.WriteLine("Enter number of columns of the array");
int wid = int.Parse(Console.ReadLine());
int[,] consecincrease = new int[len, wid];
Console.WriteLine("Enter the Values of array");
for (int index = 0; index < consecincrease.GetLength(0); index++)
{
for (int index1 = 0; index1 < consecincrease.GetLength(1); index1++)
{
consecincrease[index, index1] = int.Parse(Console.ReadLine());
Console.Write("The value of the {0} {1}" + ":" + " " + "{2}", index, index1, consecincrease[index, index1]);
Console.WriteLine();
}
}
for (int index = 0; index < consecincrease.GetLength(0); index++)
{
for (int index1 = 0; index1 < consecincrease.GetLength(1); index1++)
{
increment = 0;
checkvalue = consecincrease[index, index1];
for ( indices = increment; indices < consecincrease.GetLength(1)-1; indices++)
{
if (checkvalue < consecincrease[index, indices +1])
{
consincval = Convert.ToString(checkvalue);
count++;
maincount = count;
checkvalue = consecincrease[index, indices+1];
consincval1 = consincval1 + " " + consincval + " ";
}
}
if (count == 0)
{
}
else if (count >= 1)
{
consincval = Convert.ToString(checkvalue);
count++;
maincount = count;
consincval1 = consincval1 + " " + consincval + " ";
}
if (finalcount < maincount)
{
finalcount = maincount;
finalconsincval = consincval1;
count = 0;
consincval1 = null;
consincval = null;
}
else
{
count = 0;
consincval1 = null;
consincval = null;
}
increment ++;
}
}
Console.WriteLine();
Console.WriteLine(finalconsincval);
Console.ReadLine();
}
}
}

Creating different arrays: not displaying correct results

I am currently building a sorting program. I have made three different ways to create an array: Random, In Order and Reverse. I am currently undergoing problems with the In Order and Reverse arrays. Every time an In Order array is created it starts with a 1, I am not sure how come is doing so. Also my Reverse array will display digits out of order not every time but after some clicks. How can I fix these two issues?
namespace sortingMachine
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//Class Level Variables --------------------------------------------------------------------------------------
Stopwatch sw = new Stopwatch();
Random r = new Random();
OpenFileDialog open1 = new OpenFileDialog();
long operations = 0;
int size;
int max;
int[] createArray;
int[] sortArray;
int[] copyArray;
//Create Array Methods --------------------------------------------------------------------------------------
public void RandomNumber()
{
size = Convert.ToInt32(textBoxSize.Text);
max = Convert.ToInt32(textBoxMax.Text);
createArray = new int[size];
copyArray = new int[size];
sortArray = new int[size];
for (int i = 0; i < size; i++)
{
createArray[i] = r.Next(1, max);
}
textBoxResults.AppendText("-------------------------------------------------------------------------------" + Environment.NewLine + "Random" + Environment.NewLine + Environment.NewLine);
DisplayArrays();
}
public void InOrder()
{
size = Convert.ToInt32(textBoxSize.Text);
max = Convert.ToInt32(textBoxMax.Text);
createArray = new int[size];
copyArray = new int[size];
sortArray = new int[size];
createArray[0] = 1;
for (int i = 1; i < size; i++)
{
createArray[i] = createArray[i - 1] + r.Next(1, max);
}
for (int i = 1; i < size; i++)
{
if (r.Next(1, 101) < Convert.ToInt32(textBoxPercentage.Text))
{
for (int x = 1; x < size; x++)
{
createArray[x] = r.Next(1, createArray[size - 1]);
}
}
}
textBoxResults.AppendText("-------------------------------------------------------------------------------" + Environment.NewLine + "In Order" + Environment.NewLine + Environment.NewLine);
DisplayArrays();
}
public void ReverseOrder()
{
size = Convert.ToInt32(textBoxSize.Text);
max = Convert.ToInt32(textBoxMax.Text);
createArray = new int[size];
copyArray = new int[size];
sortArray = new int[size];
createArray[size - 1] = 1;
for (int i = size - 1; i > 0; i--)
{
createArray[i - 1] = createArray[i] + r.Next(1, max);
}
for (int i = size - 1; i > 0; i--)
{
if (r.Next(1, 101) < createArray[0])
{
for (int x = size - 1; x > 0; x--)
{
createArray[x] = r.Next(1, createArray[0]);
}
}
}
textBoxResults.AppendText("-------------------------------------------------------------------------------" + Environment.NewLine + "Reverse Order" + Environment.NewLine + Environment.NewLine);
DisplayArrays();
}
private void buttonCreateArray_Click(object sender, EventArgs e)
{
if ((textBoxSortKey.Text != "") && (textBoxCreateKey.Text != ""))
{
if (radioButtonRandom.Checked == true)
{
RandomNumber();
}
if (radioButtonInOrder.Checked == true)
{
InOrder();
}
if (radioButtonReverseOrder.Checked == true)
{
ReverseOrder();
}
}
else
{
MessageBox.Show("Type a key into the Key textbox.");
}
}
}
}
Display Results:
The order array I am not sure why it always start with one:
-------------------------------------------------------------------------------
In Order
1
2
4
6
10
There are times the reverse order array will be like this:
-------------------------------------------------------------------------------
Reverse Order
10
2
7
6
5
Windows Form:
If you look at how you are assigning values to the array you'll see that the first element is assigned zero, but in your loop you start at the second element (i.e. 1) so you never re-assign the first element.
createArray[0] = 1;
for (int i = 1; i < size; i++)
{
createArray[i] = createArray[i - 1] + r.Next(1, max);
}
Try writing the first element assignment like this:
createArray[0] = r.Next(1, max);
As for your reverse function, there's too much weirdness in there to really see what you're trying to do. Try thinking thru it a few more times. Especially be careful with code like this: if (r.Next(1, 101) < createArray[0]) - it has random behaviour and also magic numbers in it.
In the function InOrder you initialize your first index of your array to 1. As for the Reverse Order, in the if statement in between the two fors, each time you are comparing a random number between 1-101 with the first number in your array. What you should be doing instead is compare the numbers in your array with each other.

Categories

Resources