using System; using System.Collections.Generic; using System.Diagnostics;//StopWatch类的命名空间 using System.Linq; using System.Text; using System.Threading.Tasks; namespace 直接插入排序 { class Program { static void Main(string[] args) { int[] array = new int[] { 42, 20, 99, 12, 44, 4, 66, 88, 24, 93 ,1,22};//需要排序的数组 Stopwatch watch = new Stopwatch();//创建StopWatch类的对象 watch.Start();//调用类中的start函数开始计时 Bubbing(array);//用冒泡排序算法对数组进行排序 watch.Stop();//调用StopWatch类中的stop函数,终止计时 Console.WriteLine(watch.Elapsed);//输出直接插入排序的用时 foreach (var item in array)//输出已近排序好的数组 { Console.WriteLine(item); } Console.ReadKey(); } /// <summary> /// 冒泡排序,每次先把数组中的最大数排好 /// </summary> /// <param name="array"></param> public static void Bubbing(int[] array) { for (int i = 0; i < array.Length-1; i++)//记录有多少个数已近排序好了 { for (int j = 0; j < array.Length-i-1; j++)//对剩下来的数进行排序 { if(array[j]>array[j+1])//相邻两个元素之间比较,把较大的元素往后放 { int temp = array[j]; array[j] = array[j + 1]; array[j + 1] = temp; } } } } } }
对数组设置两个指针high low ,指针指向数组最后一个数和数组第一个数,low指向的数为基准值,首先在high位置前面找比基准值小的数,把该数放入low的位置,在从原low处
找比基准值大的数,放入上个交换数的位置。依此下去,直到数组的中间位置空出来,把基准值放入该位置。在把数组分成两个数组,递归本函数,以实现快速排序
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; namespace 快速排序 { class Program { static void Main(string[] args) { int[] array = new int[] { 42, 20, 99, 12, 44, 4, 66, 88, 24, 93, 1, 22 };//需要排序的数组 Stopwatch watch = new Stopwatch();//创建StopWatch类的对象 watch.Start();//调用类中的start函数开始计时 QuickSort(0,array.Length-1,array);//用快速排序算法对数组进行排序 watch.Stop();//调用StopWatch类中的stop函数,终止计时 Console.WriteLine(watch.Elapsed);//输出直接插入排序的用时 foreach (var item in array)//输出已近排序好的数组 { Console.WriteLine(item); } Console.ReadKey(); } /// <summary> /// 快速排序,确定数组的基准位,大于他的放在他的右边,小于他的放在他的左边 /// </summary> /// <param name="left"></param> /// <param name="right"></param> /// <param name="array"></param> private static void QuickSort(int left,int right,int[] array) { if(left>=right)//设置递归函数终止条件,当数组只有一个数时,终止回调 { return; } int i = left; int j = right; int temp = array[left]; if(left<right) { while(i<j) { while(i<j)//从数组尾部找比基准值小的数,放在数组首部空出的位置 { if(temp>array[j])//查找到就终止循环,把数放在数组首部空出的位置 { array[i] = array[j]; break; } else//这个数不小于基准数就左移数组一位,用来判断 { j--; } } while(i<j)//找比数组大的数 { if(temp<array[i])//找到放在数组右边空的位置上,结束查找 { array[j] = array[i]; break; } else//没找到就继续找 { i++; } } } } array[i] = temp;//把大于基准数的放在基准数的右边,小于基准数的放在左边,基准数的位置根据他左右边数的个数确定 QuickSort(left,i-1,array);//这次执行确定了基准数在数组中排序的位置,在递归函数确定基准数左边的数位置 QuickSort(i+1 , right, array);//递归函数确定基准数右边数的位置 } } }
原文:https://www.cnblogs.com/zhangyang4674/p/11333093.html