Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- public class Program
- {
- public static void Main()
- {
- int[] arr = {10, 4, 1, 9, 12, 3, 6};
- int n = arr.Length;
- Console.WriteLine("Original Array:\n");
- PrintArray(arr);
- Console.WriteLine("\n");
- SelectionSort(arr,n);
- Console.WriteLine("Sorted Array:\n");
- PrintArray(arr);
- Console.WriteLine("\n");
- // Outputs:
- //
- // Original Array:
- // 10 4 1 9 12 3 6
- //
- // Sorted Array:
- // 1 3 4 6 9 10 12
- }
- // Method to swap elements at a given index of values
- public static void Swap(int[] arr, int firstIndex, int secondIndex)
- {
- int temp = arr[firstIndex];
- arr[firstIndex] = arr[secondIndex];
- arr[secondIndex] = temp;
- }
- // Method to look for the smallest value of a given subarray
- public static int IndexOfMinimum(int[] arr, int startIndex, int n)
- {
- int minValue = arr[startIndex];
- int minIndex = startIndex;
- for(int i = minIndex + 1; i < n; i++)
- {
- if(arr[i] < minValue)
- {
- minIndex = i;
- minValue = arr[i];
- }
- }
- return minIndex;
- }
- // Method to perform Selection Sort
- public static void SelectionSort(int[] arr, int n)
- {
- for(int i = 0; i < n; i++)
- {
- int index = IndexOfMinimum(arr, i, n);
- Swap(arr, i, index);
- }
- }
- // Method to print results to console
- public static void PrintArray(int[] arr)
- {
- foreach(int num in arr)
- {
- Console.Write(num + " ");
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement