forked from TheAlgorithms/C-Sharp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinsertion_sort.cs
51 lines (45 loc) · 1.36 KB
/
insertion_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
using System;
namespace insertion_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] + " ");
}
InsertionSort(data);
Console.Write("\nSorted: ");
for (int i = 0; i < data.Length; i++)
{
Console.Write(data[i] + " ");
}
Console.ReadKey();
}
public static void InsertionSort(int[] data)
{
for (int index = 1; index < data.Length; index++)
{
for (int i = index; i > 0 && data[i] < data[i - 1]; i--)
{
Exchange(data, i, i - 1);
}
}
}
public static void Exchange(int[] data, int a, int b)
{
int temporary;
temporary = data[a];
data[a] = data[b];
data[b] = temporary;
}
}
}