SHARE
TWEET

07. SelectionSort

Teodor92 Jan 6th, 2013 463 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  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. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top