Answer the question
In order to leave comments, you need to log in
How to swap array elements?
I need to compare the 1st element of the array with other elements, find the larger one . Then write this larger one instead of 2 elements
int[] array = new[] { 1, 2, 3, 4, 5 };
int first = array[0];
int second = array[1];
foreach(int i in array)
{
if (i > first)
{
second = i;
break;
}
}
for(int q = 0; q<array.Length; q++)
{
Console.WriteLine(array[q]);
}
Console.ReadKey();
Answer the question
In order to leave comments, you need to log in
You described the bubble sort algorithm.
Its implementation:
int[] array = new[] { 1, 2, 3, 4, 5 };
int temp;
for (int i = 0; i < array.Length-1; i++)
{
for (int j = i + 1; j < array.Length; j++)
{
if (array[i] > array[j])
{
temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question