Advertisement
jyoung12387

Selection Sort

Mar 28th, 2020
348
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.44 KB | None | 0 0
  1. using System;
  2.                    
  3. public class Program
  4. {
  5.     public static void Main()
  6.     {
  7.         int[] arr = {10, 4, 1, 9, 12, 3, 6};
  8.         int n = arr.Length;
  9.        
  10.         Console.WriteLine("Original Array:\n");
  11.         PrintArray(arr);
  12.         Console.WriteLine("\n");
  13.        
  14.         SelectionSort(arr,n);
  15.        
  16.         Console.WriteLine("Sorted Array:\n");
  17.         PrintArray(arr);
  18.         Console.WriteLine("\n");
  19.        
  20.         // Outputs:
  21.         //
  22.         // Original Array:
  23.         // 10 4 1 9 12 3 6
  24.         //
  25.         // Sorted Array:
  26.         // 1 3 4 6 9 10 12
  27.  
  28.     }
  29.    
  30.     // Method to swap elements at a given index of values
  31.     public static void Swap(int[] arr, int firstIndex, int secondIndex)
  32.     {
  33.         int temp = arr[firstIndex];
  34.         arr[firstIndex] = arr[secondIndex];
  35.         arr[secondIndex] = temp;
  36.     }
  37.    
  38.     // Method to look for the smallest value of a given subarray
  39.     public static int IndexOfMinimum(int[] arr, int startIndex, int n)
  40.     {
  41.         int minValue = arr[startIndex];
  42.         int minIndex = startIndex;
  43.        
  44.            for(int i = minIndex + 1; i < n; i++)
  45.            {
  46.                 if(arr[i] < minValue)
  47.                 {
  48.                     minIndex = i;
  49.                     minValue = arr[i];
  50.                 }
  51.             }
  52.         return minIndex;   
  53.     }
  54.    
  55.     // Method to perform Selection Sort
  56.     public static void SelectionSort(int[] arr, int n)
  57.     {
  58.         for(int i = 0; i < n; i++)
  59.         {
  60.             int index = IndexOfMinimum(arr, i, n);
  61.             Swap(arr, i, index);
  62.         }
  63.     }
  64.    
  65.     // Method to print results to console
  66.     public static void PrintArray(int[] arr)
  67.     {
  68.         foreach(int num in arr)
  69.         {
  70.             Console.Write(num + " ");
  71.         }
  72.     }
  73. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement