sort类 主要逻辑
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Selection
{
public class sort
{
/**
*selection sort 原理
* 默认升序排列
* 由循环找出最小值
* 与冒泡排序不同的是--》记录下最小值的下标 而不是每比较一次交换一次
* 然后把此次循环的最小值放到数组前面
*/
public int[] selectionsort(int[] a, int n)
{
for (int j = 0; j < n - 1; j++)
{
int min_index = j;//循环令最小值的下标为j
for (int i = j; i < n; i++)
{
if (a[i] < a[min_index])
{
min_index = i;//记录下最小值的下标
}
}
int temp = a[j];
a[j] = a[min_index];
a[min_index] = temp;
Display(a, n);
}
return a;
}
/**
*冒泡排序
* 双重循环 比较
*/
public int[] bubblesort(int[] a, int n)
{
for (int i = 0; i < n; i++)
{
for (int j = i; j < n; j++)
{
if (a[i] > a[j])
{
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
Display(a, n);
}
return a;
}
//插入排序
public int[] insertionsort(int[] a, int n)
{
for (int i = 1; i < n; i++)
{
int j = i - 1;
// while 中条件的顺讯有先后
// 当j不满足就不进行a[j] 与 a[j + 1]的判断了
// 否则会越界....
while (j >= 0 && a[j] >= a[j + 1])
{
int temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
j--;
}
Display(a, n);
}
return a;
}
public void inputdata(int[] a, int n)
{
for (int i = 0; i < n; i++)
{
Console.WriteLine("please input the data u want to input!");
a[i] = Int32.Parse(Console.ReadLine());
}
}
//打印
public void print(int[] a, int n)
{
Console.WriteLine();
for (int i = 0; i < n; i++)
{
Console.WriteLine("第" + (i+1) + "个数为:" + a[i]);
}
}
//表现排序过程的打印
public void Display(int[] a, int n)
{
Console.WriteLine("\n排序过程 : ");
for (int i = 0; i < n; i++)
{
Console.Write(a[i] + " ");
}
}
//操作菜单
public void show()
{
Console.WriteLine("++++++++++++++++++++++++++++++++++++++");
Console.WriteLine("1.selectionsort");
Console.WriteLine("2.bubblesort");
Console.WriteLine("3.insertionsort");
Console.WriteLine("++++++++++++++++++++++++++++++++++++++");
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Selection
{
class Test
{
static void Main(string[] args)
{
Console.WriteLine("please input the array size");
int n = Int32.Parse(Console.ReadLine());
int[] a = new int[n];
//储存
int[] arr = new int[20];
int length = n;
sort test = new sort();
test.inputdata(a, n);
Array.Copy(a, 0, arr, 0, length);
char ch;
do
{
Console.Clear();
int key;
test.show();
Console.WriteLine("请输入您要进行的操作");
key = Int32.Parse(Console.ReadLine());
switch (key)
{
case 1:
a = test.selectionsort(a, n);
break;
case 2:
a = test.bubblesort(a, n);
break;
case 3:
a = test.insertionsort(a, n);
break;
default: break;
}
test.print(a, n);
// Console.WriteLine("数组未排序前为:");
// test.print(arr, n);
a = arr;
Console.WriteLine("您想要继续吗?Y/y");
ch = Char.Parse(Console.ReadLine());
} while ('y' == ch || 'Y' == ch);
}
}
}