Hello,

I need help!!! I have a program that uses an array for the user to enter in 5 integers. After those integers are added I want to sort them using a bubble sort. My problem is I'm really confused on where I place my bubble sort? Any help would be appreciated.Thank you!

`````` static void Main(string[] args)
{
string myName = "";
int[] integers = new int[5];
int Sum = 0;
int temp;

for (int i = 0; i < integers.Length; i++)
{
while (Sum < 10 || Sum > 50)
{
Console.WriteLine("Please enter {0}  integers between 10 and 50"
, integers.Length - i);
}
integers[i] = Sum;
Sum = 0;
}
for (int i = 0; i < integers.Length; i++)
{
for (int pass = 1; pass <= integers.Length - 2; pass++)
{
for (int j = 0; j <= integers.Length - 2; j++)
{
if (integers[j] > integers[j = 1])
{
temp = integers[j + 1];
integers[j + 1] = integers[j];
integers[j] = temp;
}
}
}
}

``````

Edited by aurgiwilllearn: changed code

4
Contributors
3
Replies
23
Views
3 Years
Discussion Span
Last Post by mridul.ahuja

Where you have it now (lines 21-34) is actually workable. The implementation has several problems with it as it stands, but you could leave it right where it is. However, that's not what you would usually do.

Has your instructor (or textbook) explained about writing separate methods other than `Main()` yet?

The usual solution to this is to write a `bubblesort()` method and pass the data to that. If you have covered methods already, then the solution is to write the `bubblesort()` method after the end of the `Main()` method, and call it in `Main()`.

Just some side notes.
change this

``````while (Sum < 10 || Sum > 50)
``````

to this

``````while (Sum > 10 || Sum < 50)
``````

and in line 27 to this

``````if (integers[j] > integers[j + 1])
``````

This should work

``````static void Main(string[] args)
{
string myName = "";
int[] integers = new int[5];
int Sum = 0;
int temp;
for (int i = 0; i < integers.Length; i++)
{
while (Sum>10 || Sum<50)
{
Console.WriteLine("Please enter {0}  integers between 10 and 50"
, integers.Length - i);
}
integers[i] = Sum;
Sum = 0;
}
for (int i = 0; i < integers.Length; i++)
{
for (int pass = 1; pass <= integers.Length - 2; pass++)
{
for (int j = 0; j <= integers.Length - 2; j++)
{
if (integers[j]>integers[j+1])
{
temp = integers[j + 1];
integers[j + 1] = integers[j];
integers[j] = temp;
}
}
}
}