Reputation:
I am currently trying to create an array and display it reverse or descending order. It currently displays a list of numbers but sometimes it does not follow the correct descending order. I believe the issues is in the if statement in between the two for loops, each time I am comparing a random number between 1-101 with the first number in your array. Instead of doing it that way, How can I compare the numbers in the array with each other? Or any suggestion in proving my reverse order array generator?
CODE
namespace reverseArray
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
long operations = 0;
int size;
int max;
int[] createArray;
int[] sortArray;
int[] copyArray;
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]);
}
}
}
}
private void buttonCreateArray_Click(object sender, EventArgs e)
{
ReverseOrder();
}
}
}
Upvotes: 0
Views: 520
Reputation: 17176
Use LINQ
using System.Linq;
namespace reverseArray
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
long operations = 0;
int size;
int max;
int[] createArray;
int[] orderedArray;
int[] orderedByDescendingArray;
public int[] CreateArray(int size, int max)
{
var result = new int[size];
Random r = new Random();
for(int i; i<size; i++)
{
result[i] = r.Next(max);
}
return result;
}
private void buttonCreateArray_Click(object sender, EventArgs e)
{
size = Convert.ToInt32(textBoxSize.Text);
max = Convert.ToInt32(textBoxMax.Text);
createArray = CreateArray(size, max);
orderedArray = array.OrderBy(a => a);
orderedByDescendingArray = array.OrderByDescending(a => a);
}
}
}
//P.S. Code may contain errors coz I typed it directly here.
Upvotes: 0
Reputation: 458
no need to use logic to create reverse order array. In C# has default method to reverse it. so used that and you can get output ..
string fullOrder= Console.ReadLine();
char[] charArray= fullOrder.ToCharArray();
Array.Reverse(charArray);
Console.WriteLine(charArray);
Console.ReadLine();
Upvotes: 0
Reputation: 100527
Consder using built methods for sorting like Array.Sort and Enumerable.OrderBy. They have variants that take comaprer to customize sorting.
Upvotes: 0
Reputation: 9879
No need to implement your own algorithm to sort or reverse an array.
Use Array.Sort and/or Array.Reverse.
To sort in descending order, first sort then reverse the array.
Upvotes: 1