Reputation: 29
Let's Say We Have an Array Of Int :
int[] array = new int[5];
and inside of this array we have a 5 randomly numbers..
array = {10,5,7,0,3};
What Would be The Best Way To Change That array To This Array By Code
array[0]=0;
array[1]=3;
array[2]=5;
array[3]=7;
array[4]=10;
For Me i Thought about Creating Two Loops One Of i and One of j..
im gonna take the position 0 (i) and compare it with All the Other Numbers in The Array. i mean The positions j which is started from (i+1) till the end of the array (array.Length).
Then When i'll found that array[i] is Upper Than array[j] Simply i'll Change The first Value with The Other...
and Of course Here i need To Declare variable To Make That Change as shown :
int[] array = new int[5]{10,5,7,0,3};
int Change;
for(int i =0;i<array.Lenght;i++)
{
for(int j =i+1;j<array.Lenght;j++)
{
if(array[i]>array[j])
{
change=array[i];
array[i] = array[j];
array[j] = change;
}
}
}
This is solve The Problem But even thought i don't Like That Logic || that Code
if you have another one Can You Tell Me About it ??
Upvotes: 0
Views: 70
Reputation: 1
You can simply use Array.Sort
method.
int[] array = new int[5] { 10, 5, 7, 0, 3 };
Array.Sort(array);
On OP's request, I am providing the optimized code. Here complexity is O(Square(N)). I would suggest you use merge sort or quick sort, these have complexity O(NLogN)
int[] array = new int[5] { 10, 5, 7, 0, 3 };
int change = 0;
for (int i = 0; i <= array.Length - 2; i++)
{
for (int j = 0; j <= array.Length - 2; j++)
{
if (array[j] > array[j + 1])
{
change = array[j + 1];
array[j + 1] = array[j];
array[j] = change;
}
}
}
Upvotes: 1