Сортировка простым выбором - C#
Формулировка задачи:
Здравствуйте! Мне нужно осуществить сортировку простым выбором для данного массива a_input= {20,-5,10,8,-3}
Помогите довести до ума код:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication2
{
class Program
{
static void Main()
{
Console.WriteLine("Введите размер массива");
int min;
int buf;
int k, f = 0, l = 0; //counters
k = int.Parse(Console.ReadLine());
int[] sample = new int[k];
Random j = new Random();
for (int i=0; i < sample.Length; i++)
{
for (int n = 0; n < k; n++)
{
sample[n] = j.Next(10);
Console.WriteLine("Элемент массива " + sample[n]);
}
min = sample[0];
foreach (int a in sample)
{
l++;
if (a < min)
{
f = l;
min = a;
}
}
Console.WriteLine("Минимальный элемент " + min + "\n" + f);
for (int n = 0; n < k; n++)
{
buf = sample[f];
sample[f] = sample[0];
sample[0] = buf;
}
Console.ReadKey();
}
}
}
}Решение задачи: «Сортировка простым выбором»
textual
Листинг программы
using System;
namespace Stupid.Sorting
{
internal class Program
{
private static void Main(string[] args)
{
test();
Console.ReadKey();
}
private static void test()
{
int[] a = gen_array(10);
Console.Write("source array : ");
print(a);
selection_sort(a);
Console.Write("sorted array: ");
print(a);
}
private static void print(int[] a)
{
Array.ForEach(a, item => Console.Write("{0} ", item));
Console.WriteLine();
}
private static int[] gen_array(int len)
{
var array = new int[len];
var r = new Random((int) DateTime.Now.Ticks & 0x0000FFFF);
for (int i = 0; i < array.Length; ++i)
{
array[i] = r.Next(-100, 100);
}
return array;
}
//вставками
private static void insert_sort(int[] a)
{
for (int i = 1; i < a.Length; ++i)
{
for (int j = i; j > 0 && a[j] < a[j - 1]; --j)
{
swap(ref a[j], ref a[j - 1]);
}
}
}
//выбором
private static void selection_sort(int[] a)
{
for (int i = 0; i < a.Length - 1; ++i)
{
int min = i;
for (int j = i + 1; j < a.Length; ++j)
{
if (a[j] < a[min])
min = j;
}
if (min != i)
swap(ref a[i], ref a[min]);
}
}
private static void swap(ref int a1, ref int a2)
{
int t = a1;
a1 = a2;
a2 = t;
}
}
}