基本排序算法:冒泡,选择,插入
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
using System; using System.Collections.Generic; using System.Text; namespace 基础排序算法 { class CArray { private int[] arr;//定义数组 private int upper;//数组上限 private int numElements;//数组元素 public CArray(int size) { arr = new int[size]; upper = size - 1; numElements = 0; } public void Insert(int item) { arr[numElements] = item; numElements++; } public void DisplayElements() { for (int i = 0; i <= upper; i++) { Console.Write(arr[i]+" "); } } public void Clear() { for (int i = 0; i <= upper; i++) { arr[i] = 0; numElements = 0; } } /// <summary> /// 冒泡排序 /// </summary> public void BubbleSort() { int temp; for (int i = upper; i > 0; i--) { for (int j = 0; j <= i - 1; j++) { if ((int)arr[j] > arr[j + 1]) { temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } } } /// <summary> /// 选择循环: /// 在选择排序算法中使用了两层循环,外层循环从数组的第一个 /// 元素移动到数组最后一个元素之前的元素, /// 而内层循环则从数组的第二个元素移动到数组的最后一个元素 /// 并且找到比当前外层循环所指元素更小的数值,在内循环遍历一遍之后, /// 就会把数组内最小值赋值到数组中合适的位置上 /// </summary> public void SelectSort() { int min, temp; for (int i = 0; i <= upper; i++) { min=i; for (int j = i + 1; j <= upper; j++) { if (arr[j] < arr[min]) arr[min] = arr[j]; } temp=arr[i]; arr[i] = arr[min]; arr[min] = temp; } } /// <summary> /// 插入排序: /// 插入排序的算法有两层循环,外层循环会逐个遍历数组元素, /// 而内层循环则会把外层循环所选择的元素与该元素在数组内的下一个元素进行比较, /// 如果外层循环选择的元素小于内层循环选择的元素, /// 那么数组元素都向右移动以便为内层循环元素留出位置 /// </summary> public void InsertSort() { int j, temp; for (int i = 1; i <= upper; i++) { temp = arr[i]; j = i; while (j > 0 && arr[j - 1] >= temp) { arr[j] = arr[j - 1]; j--; } arr[j] = temp; } } } }
通过Timing类来计算算法的效率(时间)
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
class Timing { TimeSpan duration; public Timing() { duration = new TimeSpan(0); } public void StopTime() { duration = Process.GetCurrentProcess().TotalProcessorTime; } public void StartTime() { GC.Collect(); GC.WaitForFullGCApproach(); } public TimeSpan Result() { return duration; } }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
using System; using System.Collections.Generic; using System.Text; namespace 基础排序算法 { class Program { static void Main(string[] args) { Timing t = new Timing(); CArray nums = new CArray(100000000); Random rnd = new Random(100000000); for (int i = 0; i < 1000; i++) nums.Insert(rnd.Next(0,100000000)); t.StartTime(); nums.BubbleSort(); t.StopTime(); Console.WriteLine("BubbleSort time:" + t.Result().TotalSeconds); t.StartTime(); nums.SelectSort(); t.StopTime(); Console.WriteLine("SelectSort time:" + t.Result().TotalSeconds); t.StartTime(); nums.InsertSort(); t.StopTime(); Console.WriteLine("InsertSort time:" + t.Result().TotalSeconds); Console.ReadKey(); } } }
三种排序中选择排序效率较高,冒泡此之,插入最慢