Exclusive Clothing Sale On Flipkart

Get up to 50% off on our latest collection.

Shop Now

Swap min and max element in integer array in C#

 

Swap min and max element in integer array in C#

C# Code

public static void MinMaxSwap()

        {

            int[] input = { 1, 2, 4, 5, 6, 10, 9 };

            if (input.Length == 0)

                return;

 

            int maxPos = 0;

            int minPos = 0;

            int valMax = 0;

            int valMin = 0;

 

            for (int i = 1; i < input.Length; i++)

            {

                if (input[maxPos] < input[i])

                    maxPos = i;

                if (input[minPos] > input[i])

                    minPos = i;

            }

            valMax = input[maxPos];

            valMin = input[minPos];

            input[maxPos] = valMin;

            input[minPos] = valMax;

 

            foreach (var item in input)

            {

                Console.WriteLine(item);

            }

        }



Output

Logic 2

C# Code

        public static void MinMaxSwap2()

        {

            int[] input = { 1, 2, 4, 5, 6, 10, 9 };

            int min = 0;

            int max = 0;

 

            for (int i = 1; i < input.Length; i++)

            {

                if (input[min] > input[i])

                    min = i;

                if (input[max] < input[i])

                    max = i;

            }

            int temp = input[min];

            input[min] = input[max];

            input[max] = temp;

 

            foreach (var item in input)

            {

                Console.WriteLine(item);

            }

        }


Output 


Share this

Related Posts

Previous
Next Post »

Exclusive Clothing Sale On Flipkart

Get up to 50% off on our latest collection.

Shop Now