forked from TheAlgorithms/C-Sharp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathselection_sort.cs
53 lines (49 loc) · 1.6 KB
/
selection_sort.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
using System;
namespace selection_sort
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Please enter some integers, separated by spaces:");
string input = Console.ReadLine();
string[] integers = input.Split(' ');
int[] data = new int[integers.Length];
for (int i = 0; i < data.Length; i++)
data[i] = int.Parse(integers[i]);
Console.Write("\nUnsorted: ");
for (int i = 0; i < data.Length; i++)
{
Console.Write(data[i] + " ");
}
int[] result = SelectionSort(data);
Console.Write("\nSorted: ");
for (int i = 0; i < result.Length; i++)
{
Console.Write(result[i] + " ");
}
Console.ReadKey();
}
public static int[] SelectionSort(int[] intArray)
{
int[] newArray = new int[intArray.Length];
bool[] accessed = new bool[intArray.Length];
for (int i = 0; i < intArray.Length; i++)
{
int smallest = 0;
bool set = false;
for (int j = 0; j < intArray.Length; j++)
{
if (!accessed[j] && (intArray[j] <= intArray[smallest] || !set))
{
set = true;
smallest = j;
}
}
accessed[smallest] = true;
newArray[i] = intArray[smallest];
}
return newArray;
}
}
}