Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //Sorting an array means to arrange its elements in increasing order. Write a program to sort an array. Use the "selection sort" algorithm:
- //Find the smallest element, move it at the first position, find the smallest from the rest, move it at the second position, etc.
- using System;
- class SelectionSort
- {
- static void Main()
- {
- int arrayLength;
- Console.Write("Enter the array's length: ");
- while (!int.TryParse(Console.ReadLine(), out arrayLength) || arrayLength < 0)
- {
- Console.Write("Invalid input. Enter a positive integer number: ");
- }
- int[] array = new int[arrayLength];
- for (int i = 0; i < arrayLength; i++)
- {
- Console.Write("Enter the {0} element of the array: ", i);
- while (!int.TryParse(Console.ReadLine(), out array[i]))
- {
- Console.Write("Invalid input. Enter an integer number: ");
- }
- }
- Console.WriteLine(string.Join(", ", array));
- int index = 0;
- for (int i = 0; i < array.Length - 1; i++)
- {
- int minValue = int.MaxValue;
- for (int j = i; j < array.Length; j++)
- {
- if (array[j] < minValue)
- {
- minValue = array[j];
- index = j;
- }
- }
- array[index] = array[i];
- array[i] = minValue;
- minValue = int.MaxValue;
- Console.WriteLine(string.Join(", ", array));
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement