SHARE
TWEET

Arrays - 07_SelectionSort

ntodorova Jan 18th, 2013 109 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. using System;
  2.  
  3. /*
  4.  * 7. Sorting an array means to arrange its elements in increasing order.
  5.  * Write a program to sort an array. Use the "selection sort" algorithm: Find the smallest
  6.  * element, move it at the first position, find the smallest from the rest, move it at the second position, etc.
  7.  */
  8. class SelectionSort
  9. {
  10.         static void Main()
  11.         {
  12.                 int[] array = { 3, 2, 7, 4, 5, 18, 4, 54, 32 };
  13.  
  14.                 int minKeyElement = 0;
  15.                 int tmpElement = int.MinValue;
  16.  
  17.                 for (int j = 0; j < array.Length - 1; j++)
  18.                 {
  19.                         minKeyElement = j;
  20.  
  21.                         for (int p = j + 1; p < array.Length; p++)
  22.                         {
  23.                                 if (array[p] < array[minKeyElement])
  24.                                 {
  25.                                         minKeyElement = p;
  26.                                 }
  27.                         }
  28.  
  29.                         tmpElement = array[minKeyElement];
  30.                         array[minKeyElement] = array[j];
  31.                         array[j] = tmpElement;
  32.                 }
  33.  
  34.                 // Sorted array
  35.                 for (int i = 0; i < array.Length; i++)
  36.                 {
  37.                         Console.WriteLine(array[i]);
  38.                 }
  39.         }
  40. }
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