C# Bubble sort error? [duplicate] - c#

This question already has answers here:
What is an IndexOutOfRangeException / ArgumentOutOfRangeException and how do I fix it?
(5 answers)
Closed 5 years ago.
What's the problem here? I have a block with 2500 random number and i want to sort them with bubble sort. But when I run the program I've got this:
System.IndexOutOfRangeException
error code after this:
if (szamok[i] > szamok[i + 1]).
(Sorry for bad English :/)
int r = 2500;
int seged;
while (r > 1)
{
for (int i = 0; i < 2500; i++)
{
if (szamok[i] > szamok[i + 1])
{
seged = szamok[i + 1];
szamok[i + 1] = szamok[i];
szamok[i] = seged;
}
}
r = r - 1;
}

The error says it: Your index is out of range. You are trying to access an element in your array after the last element in this array.
The line szamok[i] > szamok[i + 1] seems to be the culprit. +1 is one too many.
Try changing you loop so you don't visit the last element but only the second to last:
for (int i = 0; i < (2500-1); i++)

Related

System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection. (Parameter 'index') [duplicate]

This question already has answers here:
What is an IndexOutOfRangeException / ArgumentOutOfRangeException and how do I fix it?
(5 answers)
Closed 2 years ago.
I'm getting the following error when executing selenium C# code in my test script
System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection. (Parameter 'index')
at System.Collections.Generic.List`1.get_Item(Int32 index)
What does this mean? What is the problem in my code?
// Access the project
IList<IWebElement> allRows = driver.FindElements(By.XPath("//*[#id='GridViewProjList_ctl00']/tbody/tr"));
IList<IWebElement> allPages = driver.FindElements(By.XPath("//div[#class='rgWrap rgNumPart']//a"));
string projectName = "TITAN";
for (int i = 0; i <= (allPages.Count); i++)
{
allRows = driver.FindElements(By.XPath("//*[#id='GridViewProjList_ctl00']/tbody/tr"));
for (int row = 1; row <= (allRows.Count); row++)
{
projectName = "TITAN";
IWebElement nameElement = driver.FindElement(By.XPath("//table/tbody/tr/td[2]/div/div/div/table/tbody/tr[3]/td/div/div/div/div[2]/table/tbody/tr[" + row + "]/td[1]"));
string name = nameElement.Text;
if (projectName.Contains(name))
{
nameElement = driver.FindElement(By.XPath("//table/tbody/tr/td[2]/div/div/div/table/tbody/tr[3]/td/div/div/div/div[2]/table/tbody/tr[" + row + "]/td[1]"));
nameElement.Click();
break;
}
allPages = driver.FindElements(By.XPath("//div[#class='rgWrap rgNumPart']//a"));
}
allPages = driver.FindElements(By.XPath("//div[#class='rgWrap rgNumPart']//a"));
driver.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(5);
allPages.ToList()[i].Click();
Thread.Sleep(3000);
}
Thread.Sleep(3000);
Console.WriteLine($"{projectName} project has been successfully accessed");
Thread.Sleep(3000);
The thing is, your list size is not guaranteed to be the same during iteration:
The iterator is based on the allPages:
for (int i = 0; i <= (allPages.Count); i++)
Also note Guru Stron's comment here and correct the iterator bounds:
Also there is error in the length check, cause collections are zero-based it should be for (int i = 0; i < (allPages.Count); i++)
But the list is overridden multiple times, e.g.:
allPages = driver.FindElements(By.XPath("//div[#class='rgWrap rgNumPart']//a"));
And here you use the original indexer again:
allPages.ToList()[i].Click();
If the new list item count is less than i-1, you'll run into this error.
The solution is to not overwrite the list, or check the length when accessing the i-th element.

Index Out Of Range while comparing two array elements [duplicate]

This question already has answers here:
What is an IndexOutOfRangeException / ArgumentOutOfRangeException and how do I fix it?
(5 answers)
Closed 7 years ago.
This is a part of a bigger problem I'm trying to solve, but index out of range exception seems to be an invisible hurdle to me.
This if loop works well in c++ but in c#, idk whats happening. Any help is appreciated. This is very important to me. Please find the root for this exception.
namespace damn
{
class Program
{
static void Main(string[] args)
{
string InputString = Console.ReadLine();
string[] stringArray = InputString.Split(',');
int[] intArray = new int[stringArray.Length];
for (int i = 0; i < stringArray.Length; i++)
{
intArray[i] = int.Parse(stringArray[i]);
}
int length = stringArray.Length;
for(int i=0; i<length; i++)
{
if (intArray[i] > intArray[i + 1])
Console.WriteLine("ok");
else
Console.WriteLine("not ok");
}
}
IndexOutOfRangeException was unhandeled.But how? the logic is right, ain't it?
Call me a noob or what ever, this is not the actual program, but a part of it.
input sample -
1,2,3,4 [/enter/]
You have int Array[i + 1] where i goes one less than length so for last item you will have out of range as array is zero-based index; end loop 2 less then length so that intArray[i + 1] wont go out of range.
for(int i=0; i<length-1; i++)
your second loop is out of range doens't matter if you're using C++ or C#. it's just that iin C++ you have to manage your own memory space and it doesn't throw index out of range error; so you need to know when to stop in C++.
Let's get back to your code:
for(int i=0; i<length; i++)
{
if (intArray[i] > intArray[i + 1])
Console.WriteLine("ok");
else
Console.WriteLine("not ok");
}
When i == length - 1 which is your last true condition, i+1 is out of range of the array because i + 1 = length; and in C# index starts from 0.
to fix just simply change your second loop condition to i < length - 1 instead of i < length

Loop to write a cimma separated list of items [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I need to write a for loop that prints 49 through 1, with each value separated by a comma. So, it must not print a comma after the last value.
I have this so far and have no clue , after an hour of research, what else to do.
For (int i = 49; i >= 1; i--)
{
Console.WriteLine(i + ",");
}
Just check where you are in your loop to know if you need to print the comma.
public static void Test()
{
for (int i = 49; i >= 1; i--)
{
Console.WriteLine(i + (i != 1 ? "," : ""));
}
Console.ReadLine();
}
Check if you are at the last item, and don't write the comma in that case:
for (int i = 49; i >= 1; i--) {
Console.Write(i);
if (i > 1) {
Console.Write(",");
}
Console.WriteLine();
}
(There are alternatives that are a little more elegant, but this is closest to your original code. You can for example write the comma before the number and skip the first comma.)
You can use String.Join
List<string> numbers = new List<string>();
for (int i = 49; i >= 1; i--) {
numbers.Add(i.ToString());
}
string numberWithCommas = String.Join(",", numbers);
Console.WriteLine(numberWithCommas);
Or you can put in a if condition to check for the last element and conditionally print your comma.
The String.Join would be a neater way to do this operation. However as pointed out by #CommuSoft, if you are doing this operation for a large list of numbers, the memory used may be high in this operation.
Try this:
for (int i = 49; i >= 1; i--)
{
Console.Write("{0}{1}", i, i == 1 ? string.Empty : ",");
}
Your not keeping track of your value.
var content = String.Empty;
for(var i = 49; i >= 1; i--)
content += (i + ",");
Console.WriteLine(content);
Once you have a value, then you apply it. The problem your having is the scope never remains, it applies to a new line.
The value of i determines when to add the comma:
For (int i = 49; i >= 1; i--)
{
Console.WriteLine(i >= 1 ? i + "," : i);
}

What is Insertion Sort? [duplicate]

This question already has answers here:
Insertion Sorting c#
(3 answers)
Closed 10 years ago.
I am new to programming and just heard about sorting. I went through the basics of sorting and found out that Insertion Sorting is the easiest. But the thing is that I don't get what it is! Can you explain me in detail what is insertion sort and how to implement it. Implementation in c# would be appreciated more.
Any help would be greatly appreciated! :)
Take a loot at Wikipedia
The algorithm for insertion-sort is
int temp, j;
for (int i=1; i < vector.length; i++){
temp = vector[i];
j = i-1;
while (j >= 0 && vector[j] > temp){
vector[j + 1] = vector[j];
j--;
}
vector[j+1] = temp;
}
Insertion sort is more efficient than the alogrithms we have implemented before (Bubble Sort and Selection sort) for sorting a small data set. Insertion sort is mostly used when the list is partially sorted. We assume the 1st element is sorted. Then we check adjacent index for smaller or greater value. If the value is smaller, we insert it in the left side of index[0] which means now smaller value is at index[0] and if it's greater than the original value of index[0] then we get a sorted list of 2 elements. We implement same approach to adjacent elements. Then compare it to previous elements to create a sorted list. So basically - you'll end up with sorted list on the left side of the array and unsorted on the right at one stage. Remember we go back and check if the array is sorted - we do not go forward unless the array behind the concerned element (incl. concerned element) is completely sorted.
Here's the C# implementation of Insertion Sort:
class Program
{
static void Main(string[] args)
{
int i, j;
int[] unsortedarrayed = new int[] { 34, 36, 2, 7, 8, 3, 6, 5 };
for (i = 0; i < unsortedarrayed.Length; i++)
{
Console.WriteLine(unsortedarrayed[i]);
}
int[] sortedarray = InsertionSorted(unsortedarrayed);
for (i = 0; i < sortedarray.Length; i++)
{
Console.WriteLine(sortedarray[i]);
}
Console.Read();
}
public static int[] InsertionSorted(int[] unsortedarrayed)
{
for (int i = 1; i < unsortedarrayed.Length; i++)
{
int temp = unsortedarrayed[i];
int j = i - 1;
while ((j > -1) && (unsortedarrayed[j] > temp))
{
int tempo = unsortedarrayed[j + 1];
unsortedarrayed[j + 1] = unsortedarrayed[j];
unsortedarrayed[j] = tempo;
j = j - 1;
}
}
return unsortedarrayed;
}
}
Source :
For more detail click on following links :
1) Link 1
2) Link 2

Linear Search Problem [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
My program has no compile errors but the output is incorrect. Example input:
size of array: 5
input numbers: 5 4 3 2 1
//sorted: 1 2 3 4 5
search: 1
output: number 1 found at index 4
the output should be number 1 found at index 0 since the numbers were sorted already. How will I change it to this.
int[] nums = new int[100];
int SizeNum;
bool isNum = false;
private void ExeButton_Click(object sender, EventArgs e)
{
int i, loc, key;
Boolean found = false;
string SizeString = SizeTextBox.Text;
isNum = Int32.TryParse(SizeString, out SizeNum);
string[] numsInString = EntNum.Text.Split(' '); //split values in textbox
for (int j = 0; j < numsInString.Length; j++)
{
nums[j] = int.Parse(numsInString[j]);
}
if (SizeNum == numsInString.Length)
{
Array.Sort(numsInString);
key = int.Parse(SearchTextBox.Text);
ResultText.AppendText("Sorted: ");
for (i = 0; i < SizeNum; i++)
ResultText.AppendText(" " + numsInString[i]);
ResultText.AppendText("\n\n");
{
for (loc = 0; loc < SizeNum; loc++)
{
if (nums[loc] == key)
{
found = true;
break;
}
}
if (found == true)
ResultText.AppendText("Number " + key + " Found At Index [" + loc + "]\n\n");
else
ResultText.AppendText("Number " + key + " Not Found!\n\n");
}
}
}
You're sorting numsInString but then searching nums. nums is being populated before the search, so you're seeing the results of searching the unsorted numbers.
Once you've parsed numsInStrings into nums, you should be working with the latter array only. Make sure that's the one you're sorting and searching through.
In other words, once you replace the current sort call with
Array.Sort(nums);
your code will be fine.
Updated:
You actually need another fix. Right now, you're initializing nums to be an array of size 100. By default, each element will be 0. So even though you put numbers in the first five elements, when you sort the array, you end up with 95 0's, followed by 1 2 3 4 5.
You should delay initializing nums until you've seen how big numsInString is:
string[] numsInString = EntNum.Text.Split(' '); //split values in textbox
nums = new int[numsInString.Length];
for (int j = 0; j < numsInString.Length; j++)
{
nums[j] = int.Parse(numsInString[j]);
}
Now when you sort nums, you'll see only the numbers you entered.
you are sorting the numsInString array, but still searching into the nums array.
for (loc = 0; loc < SizeNum; loc++)
{
if (numsInString[loc] == key)
{
found = true;
break;
}
}
You're parsing numsInString then you're sorting it. (I suspect the sort won't do what you want, either.)
I think you really want to be sorting nums instead:
Array.Sort(nums);
Having said that, there are simpler ways of achieving the end result - such as using IndexOf to find the index of a value in an array.
It's also rather unclear why you've got braces here:
for (i = 0; i < SizeNum; i++)
ResultText.AppendText(" " + numsInString[i]);
ResultText.AppendText("\n\n");
{
...
}
That makes it look like you've got a loop with a body, but it's actually equivalent to:
for (i = 0; i < SizeNum; i++)
{
ResultText.AppendText(" " + numsInString[i]);
}
ResultText.AppendText("\n\n");
{
...
}
... the braces serve no purpose here, and merely harm readability.

Categories