Algorithm: Selection Sort

Selection Sort is a sorting algorithm that uses selection to sort an array (hence the name). If we have an array of 30 length, we loop through all the entries in the array and find the smallest number. Then you swap it around with the current entry you are looping on. Here is the algorithm:

            int amount = 10;

            int[] array = new int[amount];

            for (int a = 0; a < amount; a++ )

            {

                array[a] = Int32.Parse(Console.ReadLine());

            }

            Console.WriteLine(“Sorting…”);

            int minimum;

            for (int position = 0; position < array.Length; position++)

            {

                minimum = position;

                for (int b = (position + 1); b < array.Length; b++ )

                {

                    if (array[b] < array[minimum])

                    {

                        minimum = b;

                    }

                }

                if (minimum != position)

                {

                    int temp = array[position];

                    array[position] = array[minimum];

                    array[minimum] = temp;

                }

            }

Firstly we initialize some int variables and an array of any length. We then do a for loop, looping through all the entries in the array. We then nest another for loop to get the entry that’s index is 1 more than the current entry. This is to check for the smallest number. We check the current entry with all the other entries to find the smallest number and we set the int minimum to it. After we check all the entries, we then swap them around if they are not the same.

That was the Selection Sort algorithm, made by me (o-notation). If you have any questions/suggestions please message me.

Thanks. 

Loading more posts...