i wrote i quicksort algorithm in c# but it has a problem,when i compile it,it doesnt work in some conditions for example when i enter number 12,32,11 in textbox6 to sort, it gives out of range error when i go to trace it, debugger shows that num[] took nums[0]=12,nums[1]=11,nums[2]=1
Edited:
i changed the while condition and it know doesnt give out of range error but when the input is 12,32,11 output 11,12,1
private void button5_Click(object sender, EventArgs e)
{
string[] x = textBox6.Text.Split(',');
int[] nums = new int[x.Length];
for (int counter = 0; counter < x.Length; counter++)
{
nums[counter] = Convert.ToInt32(x[counter]);
}
int i = 0;
int j = nums.Length;
int pivot = nums[0];
do
{
do
{
i++;
}
while ((i < nums.Length) && (nums[i] < pivot));
do
{
j--;
}
while (nums[j]>pivot);
if (i < j)
{
int temp = i;
nums[i] = nums[j];
nums[j] = temp;
}
}while(i<j);
int temp1 = nums[0];
nums[0] = nums[j];
nums[j] = temp1;
int pivotpoint = j;
string QuickSort = "";
foreach (var n in nums)
QuickSort += n.ToString() + ",";
textBox5.Text = QuickSort;
}
Your issue is that i isn't being bounds-checked in your do-while loop. i will get incremented beyond the end of your nums array. Try modifying the while condition thus:
while ((i<nums.Length) && (nums[i]<pivot))
Of course you could simply use Array.Sort(nums);
Related
I have a method that is an "Improved version of Selection Sort". However, the code is not running as " temp[x] = 0;" this line gives an out of bounds of the array error. I do not want to use an ArrayList. How would I change this line to be in bounds of the array?
public static void ImprovedSelectionSort(int[] Array)
{
Stopwatch timer = new Stopwatch();
timer.Start();
int[] temp = new int[Array.Length];
for (int x = 1; x <= Array.Length; x++)
{
//OtherList.Add(0); -- what I want to do
temp[x] = 0;
}
int n = Array.Length;
int i = 0;
while (i < n)
{
int rear = 0;
int curMax = Array[i];
temp[rear] = i;
int j = i + 1;
while (j < n)
{
if (curMax < Array[j])
{
curMax = Array[j];
rear = -1;
}
if (curMax == Array[j])
{
rear = rear + 1;
temp[rear] = j;
}
j++;
}
int front = 0;
int p = Array[temp[front]];
while (front <= rear)
{
int temporary = p;
Array[temp[front]] = Array[i];
Array[i] = temporary;
i++;
front += 1;
}
}
for (int x = 1; x <= Array.Length; x++)
This is most likely the issue. The last index in an array is the length minus 1 (so, a 52-card deck goes from 0..51). Changing the "x <= Array.Length" component to "x < Array.Length" should fix the issue.
Change the <= to < in the for loop. This is a common mistake among novice devs, and not something you should sweat. But it's a good thing to keep in mind for the future.
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
using System;
namespace G09 {
class Reverse {
static void Main()
{
Console.WriteLine(ReverseText(24));
Console.ReadKey();
}
static string ReverseText(int n) {
if (n < 1)
{
return "";
}
string index = "1";
string revIndex = "";
int count = 1;
string[] arr = new string[n];
for (int i = 0; i < n; i++)
{
arr[i] = index + revIndex;
for (int j = 0; j <= i; j++)
{
if (count > 8)
{
index = index + 0;
count = 0;
break;
}
index = index + (count++ + 1).ToString();
break;
}
revIndex = "";
for (int k = index.Length - 1; k >= 0; k--)
{
if (k == index.Length - 1)
{
continue;
}
revIndex += index[k];
}
}
return string.Join("\n", arr);
}
}
}
/tmp/csharp117013-18-5s54om.vh6mt2o6r/code.cs(10,41): warning CS0162:
Unreachable code detected
Can anyone tell me why this code is unreachable on line 23??
I can not understand... In visual studio it works fine, but in other shows error.
The j++ is pointless because of the break at the end, remove one of both
for (int j = 0; j <= i; j++) {
...
break;
}
You will never increment j because you break the iteration after the first loop
for (int j = 0; j <= i; j++) //<- Error here, j++ will never be reached
{
if (count > 8)
{
index = index + 0;
count = 0;
break;
}
index = index + (count++ + 1).ToString();
break; //you leave the for loop here
}
Your issue is with this for loop:
for (int j = 0; j <= i; j++) {
if (count > 8) {
index = index + 0;
count = 0;
break;
}
index = index + (count++ + 1).ToString();
break;
}
I'm guessing the for loop starts on line 23. Because you have all paths inside the for loop containing break statements the j++ part of the for loop will never be hit. The loop will execute once and break out before ever hitting the increment for variable j.
Its been bugging me for hours because it is always returning 0 at numbers[i] and I cant figure out the problem. code worked for a different program but I had to change it so it could have a custom array size and that's when everything went wrong.
any help would be great.
Thanks in advance.
int[] numbers = new int[Convert.ToInt16(TxtArray.Text)];
int j = 0;
for (j = numbers.Length; j >= 0; j--)
{
int i = 0;
for (i = 0; i <= j - 1; i++)
{
string NumbersInput = Microsoft.VisualBasic.Interaction.InputBox("Enter Numbers to be sorted",
"Numbers Input", "", -1, -1);
numbers[i] = Convert.ToInt16(NumbersInput);
//returns 0 in if statement
if (numbers[i] < numbers[i + 1])
{
int intTemp = 0;
intTemp = numbers[i];
numbers[i] = numbers[i + 1];
numbers[i + 1] = intTemp;
}
}
}
for (int i = 0; i < numbers.Length; i++)
{
LstNumbers.Items.Add(numbers[i]);
}
private void button1_Click(object sender, EventArgs e)
{
int sizeOfArrayInt = Convert.ToInt32(arraySize.Text);
int[] array = new int[sizeOfArrayInt];
string numbers = arrayValues.Text;
string[] numbersSplit = numbers.Split(',');
int count = 0;
foreach (string character in numbersSplit)
{
int value;
bool parse = Int32.TryParse(character, out value);
if (value != null)
{
array[count] = value;
}
count++;
}
array = this.SortArray(array);
foreach (int item in array)
{
this.listBox.Items.Add(item);
}
}
private int[] SortArray(int[] arrayToSort)
{
//int[] sortedArray = new int[arrayToSort.Length];
int count = arrayToSort.Length;
for (int j = count; j >= 0; j--)
{
int i = 0;
for (i = 0; i <= j - 2; i++)
{
if (arrayToSort[i] < arrayToSort[i + 1])
{
int intTemp = 0;
intTemp = arrayToSort[i];
arrayToSort[i] = arrayToSort[i + 1];
arrayToSort[i + 1] = intTemp;
}
}
}
return arrayToSort;
}
strong text
This I got to work as a Windows Form and the output displays in the list box as each array item or individual i iteration over the array. Of course there is no error checking. Hope that helps.
Setting aside the strangeness of how you are working with text boxes, your problem with throwing an exception would happen even without them because it lies here, in your inner loop:
for (i = 0; i <= j - 1; i++)
Suppose that numbers.Length == 2. This means that j == 2. So on the first time through the outer loop, you hit the inner loop with these conditions. The first time through, i == 0. You get to the if statement:
if (numbers[i] < numbers[i + 1])
numbers[0] exists, and numbers[1] exists, so this iteration goes through fine and i is incremented.
Now i == 1. Now the loop checks its boundary condition. i <= j - 1 == true, so the loop continues. Now when you hit that if statement, it tries to access numbers[i + 1], i.e., numbers[2], which does not exist, throwing an IndexOutOfRangeException.
Edit: Came back and realized that I left out the solution (to the exception, anyway). For the bubble sort to work, your inner loop's boundary condition should be i <= j - 2, because j's initial value is == numbers.Length, which is not zero-based, while array indexes are.
Second Edit: Note that just using a List won't actually solve this problem. You have to use the right boundary condition. Trying to access list[list.Count()] will throw an ArgumentOutOfRangeException. Just because a List will dynamically resize doesn't mean that it will somehow let you access items that don't exist. You should always take time to check your boundary conditions, no matter what data structure you use.
This code is buggy but can't figure out why ... want to populate an array with 7 unique random integers without using arraylists or linq! I know the logic is not okay...
class Program
{
static void Main(string[] args)
{ int current;
int[] numbers = new int[7]; // size of that array
Random rNumber = new Random();
current = rNumber.Next(1, 50);
numbers[0] = current;
Console.WriteLine("current number is {0}", current);
for (int i=1;i<7;i++)
{
current = rNumber.Next(1, 50);
for (int j = 0; j < numbers.Length; j++)
{
do
{
if (current == numbers[j])
{
Console.WriteLine("Duplicate Found");
current = rNumber.Next(1, 50);
}
else
{
numbers[j++] = current;
break;
}
}while (current == numbers[j]);
}//inner for
}//outer for
for (int l = 0; l < 7; l++) // DISPLAY NUMBERS
{
Console.WriteLine(numbers[l]);
}
}// main
}//class
want to populate an array with 7 unique integers without using
arraylists or linq!
int[] list = new int[7];
for (int i = 0; i < list.Length; i++)
{
list[i] = i;
}
EDIT
I changed your inner loop, if the random number is already in the array; create a new random and reset j to 0.
for (int i = 1; i < 7; i++)
{
current = rNumber.Next(1, 50);
for (int j = 0; j < numbers.Length; j++)
{
if (current == numbers[j])
{
Console.WriteLine("Duplicate Found");
current = rNumber.Next(1, 50);
j = 0; // reset the index iterator
}
}//inner for
numbers[i] = current; // Store the unique random integer
}//outer for
I presume you are looking for random numbers, so the other answer is not what you are looking for.
There are a couple of issues here.
The inner loop is testing for duplicates. However, it is looking from 0 through the end of the array since it is using numbers.length. This should probably be i, to compare with already set values. numbers.length is always 7 regardless of whether or not you set any of the elements.
the assignment is using j, so presuming the first element is not a duplicate, it will be overwritten each time. That should be numbers[i] = current;. No ++ necessary as the for is handling the incrementing.
if you determine that a number is a duplicate, j should be reset to zer to check against the entire list again rather than having the while in the middle.
Without a complete rewrite, the changes will look something like this:
for (int i=1;i<7;i++)
{
current = rNumber.Next(1, 50);
for (int j = 0; j < i; j++) //----------------- loop through set values
{
if (current == numbers[j])
{
Console.WriteLine("Duplicate Found");
current = rNumber.Next(1, 50);
j = 0; // -----------------------reset the counter to start over
}
}//inner for
// if we got here there is no duplicate --------------------------------
numbers[i] = current;
}//outer for
(Please note that I have not tested this code, just added the changes)
you keep overwriting the same indexes in the else, and also checking too many indices causing the first to show up as a duplicate at all times which was false...
change it to:
for (int i=1;i<7;i++)
{
current = rNumber.Next(1, 50);
for (int j = 0; j < i; j++) ///< change to j < i. no need to check the others
{
do
{
if (current == numbers[j])
{
Console.WriteLine("Duplicate Found");
current = rNumber.Next(1, 50);
}
else
{
numbers[i] = current; ///< not j++ but i to prevent writing at the same locations over and over again
break;
}
}while (current == numbers[j]);
}//inner for
}//outer for
What about this?
int[] list = new int[7];
var rn = new Random(Environment.TickCount);
for (int i = 0; i < 7; i++)
{
var next = rn.Next(1, 50);
while(Contains(list, next))
{
next = rn.Next(1, 50);
}
list[i] = next;
}
private bool Contains(IEnumerable<int> ints, int num)
{
foreach(var i in ints)
{
if(i = num) return true;
}
return false;
}