Advertisement
sylviapsh

Selection Sort Of an Array

Jan 9th, 2013
37
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 0.96 KB | None | 0 0
  1. using System;
  2. class SelectionSortOfArray
  3. {
  4.   static void Main()
  5.   {
  6.     //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.
  7.  
  8.     int[] myArray = {2,5,4,7,8,12,5};
  9.     int minElement = 0,
  10.         minIndex = 0,
  11.         sortBuffer = 0;
  12.  
  13.     for (int i = 0; i < myArray.Length; i++)
  14.     {
  15.       minElement = myArray[i];
  16.       for (int j = i; j < myArray.Length; j++)
  17.       {
  18.         if (myArray[j] < minElement)
  19.         {
  20.           minElement = myArray[j];
  21.           minIndex = j;
  22.         }
  23.       }
  24.       sortBuffer = myArray[i];
  25.       myArray[i] = minElement;
  26.       myArray[minIndex] = sortBuffer;
  27.      
  28.     }
  29.  
  30.     for (int index = 0; index < myArray.Length; index++)
  31.     {
  32.       Console.Write("{0} ", myArray[index]);
  33.     }
  34.   }
  35. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement