Advertisement
Teodor92

07. SelectionSort

Jan 6th, 2013
536
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.11 KB | None | 0 0
  1. /* Sorting an array means to arrange
  2.  * its elements in increasing order.
  3.  * Write a program to sort an array.
  4.  * Use the "selection sort" algorithm:
  5.  * Find the smallest element, move it at the
  6.  * first position, find the smallest from the
  7.  * rest, move it at the second position, etc.
  8.  */
  9.  
  10. using System;
  11.  
  12. class SelectSort
  13. {
  14.     static void Main()
  15.     {
  16.         int[] myArray = { 9, 8, 7, 6, 5, 4, 3, 2, 1, 11, 132, 45, -2, 333 };
  17.         for (int i = 0; i < myArray.Length - 1; i++)
  18.         {
  19.             int elmMin = i;
  20.             for (int j = i + 1; j < myArray.Length; j++)
  21.             {
  22.                 if (myArray[j]<myArray[elmMin])
  23.                 {
  24.                     elmMin = j;
  25.                 }
  26.             }
  27.             if (elmMin != i)
  28.             {
  29.                 int temp = 0;
  30.                 temp = myArray[i];
  31.                 myArray[i] = myArray[elmMin];
  32.                 myArray[elmMin] = temp;
  33.             }
  34.         }
  35.         for (int i = 0; i < myArray.Length; i++)
  36.         {
  37.             Console.Write("{0}, ",myArray[i]);
  38.         }
  39.         Console.WriteLine();
  40.     }
  41. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement