【C#实现各类排序算法】

来源:互联网 发布:我的世界建筑比赛知乎 编辑:程序博客网 时间:2024/05/04 09:37
//把一些自己现在能够实现的排序算法合并一下,做一个记录和积累吧!using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace Lib{ public class Sort { /// /// 插入递增排序 /// /// 排序前数组 /// 排序后数组 public int[] Insert(int[] unsortarray) { int[] insertResult = new int[unsortarray.Length]; insertResult[0] = unsortarray[0]; for (int i = 1; i < insertResult.Length; i++) { int key = unsortarray[i]; int j = i - 1; while (j >= 0 && insertResult[j] > unsortarray[i]) { insertResult[j + 1] = insertResult[j]; j = j - 1; } insertResult[j + 1] = key; } return insertResult; } /// /// 选择递增排序 /// /// 排序前数组 /// 排序后数组 public int[] Selection(int[] sortarray) { int loopLimits = 0; int temp; while (loopLimits < sortarray.Length) { for (int i = loopLimits + 1; i < sortarray.Length; i++) { if (sortarray[i] < sortarray[loopLimits]) { temp = sortarray[loopLimits]; sortarray[loopLimits] = sortarray[i]; sortarray[i] = temp; } } loopLimits++; } return sortarray; } /// /// 冒泡递增排序 /// /// 排序前数组 /// 排序后数组 public int[] Bubble(int[] sortarray) { for (int i = 0; i < sortarray.Length; i++)//每轮比较后增1,减少后面比较的个数 { for (int j = 0; j < sortarray.Length - 1 - i; j++) //每次比较相邻两个数字,较大者排后 { if (sortarray[j] > sortarray[j + 1]) { int temp = sortarray[j]; sortarray[j] = sortarray[j + 1]; sortarray[j + 1] = temp; } } } return sortarray; } /// /// 快速递增排序 /// /// 排序前数组 /// 数组头 /// 数组尾 /// public int[] Quick(int[] array, int p, int r) { if (p < r) { int q = Partition(array, p, r); Quick(array, p, q - 1); Quick(array, q + 1, r); } return array; } /// /// 快速排序辅助函数 /// /// 数组 /// 数组头 /// 数组尾 /// public int Partition(int[] array, int p, int r) { int x = array[r]; int i = p - 1; int temp = 0; for (int j = p; j < r; j++) { if (array[j] < x) { i++; temp = array[j]; array[j] = array[i]; array[i] = temp; } } temp = array[i + 1]; array[i + 1] = array[r]; array[r] = temp; return i + 1; } /// /// 计数递增排序,适用于 /// /// 排序前数组 /// 排序后数组 public int[] Counting(int[] array) { int maxvalue = array[0]; //最多n-1次遍历找到最大值 for (int i = 1; i < array.Length; i++) { if (array[i] > maxvalue) { maxvalue = array[i]; } } //声明一个长度为最大值+1的数组 int[] newarray = new int[maxvalue+1]; //遍历该新数组,赋值为0 for (int i = 0; i < newarray.Length; i++) { newarray[i] = 0; } //遍历排序前数组,计算每一个值出现的次数,存入暂存数组中 for (int i = 0; i < array.Length; i++) { newarray[array[i]]++; } //遍历暂存数组,计算每一个元素前最多有几个元素,方便后面排序时知道数据的正确位置 for (int i = 1; i < newarray.Length; i++) { newarray[i] = newarray[i] + newarray[i - 1]; } //声明一个长度与排序数组长度一样的数组,用来存放排序后的数组 int[] resultarray = new int[array.Length]; //遍历数组,进行安放数据,同时每次将暂存数组对应的值自减一 for (int i = 0; i < resultarray.Length; i++) { resultarray[newarray[array[i]]-1] = array[i]; newarray[array[i]]--; } return resultarray; } }}
0 0
原创粉丝点击