Advertisement
TanyaPetkova

C# Part II Arrays Exercise 7

Dec 21st, 2013
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.57 KB | None | 0 0
  1. //Sorting an array means to arrange its elements in increasing order. Write a program to sort an array. Use the "selection sort" algorithm:
  2. //Find the smallest element, move it at the first position, find the smallest from the rest, move it at the second position, etc.
  3.  
  4. using System;
  5.  
  6. class SelectionSort
  7. {
  8.     static void Main()
  9.     {
  10.         int arrayLength;
  11.  
  12.         Console.Write("Enter the array's length: ");
  13.  
  14.         while (!int.TryParse(Console.ReadLine(), out arrayLength) || arrayLength < 0)
  15.         {
  16.             Console.Write("Invalid input. Enter a positive integer number: ");
  17.         }
  18.  
  19.         int[] array = new int[arrayLength];
  20.  
  21.         for (int i = 0; i < arrayLength; i++)
  22.         {
  23.             Console.Write("Enter the {0} element of the  array: ", i);
  24.  
  25.             while (!int.TryParse(Console.ReadLine(), out array[i]))
  26.             {
  27.                 Console.Write("Invalid input. Enter an integer number: ");
  28.             }
  29.         }
  30.  
  31.         Console.WriteLine(string.Join(", ", array));
  32.  
  33.         int index = 0;
  34.  
  35.         for (int i = 0; i < array.Length - 1; i++)
  36.         {
  37.             int minValue = int.MaxValue;
  38.  
  39.             for (int j = i; j < array.Length; j++)
  40.             {
  41.                 if (array[j] < minValue)
  42.                 {
  43.                     minValue = array[j];
  44.                     index = j;
  45.                 }
  46.             }
  47.             array[index] = array[i];
  48.             array[i] = minValue;
  49.             minValue = int.MaxValue;
  50.  
  51.             Console.WriteLine(string.Join(", ", array));
  52.         }
  53.     }
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement