A
A
Anton_repr2020-05-18 20:42:13
C++ / C#
Anton_repr, 2020-05-18 20:42:13

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();

But for some reason the original array is displayed

Answer the question

In order to leave comments, you need to log in

1 answer(s)
C
Collin, 2020-05-19
@Anton_repr

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;
                    }
                }
            }

Now just apply this algorithm to your specific problem.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question