namespace temp
{
public class QuickSort
{
/// <summary>
/// 排序
/// </summary>
/// <param name="numbers">;待排序数组</param>
/// <param name="left">;数组第一个元素索引Index</param>
/// <param name="right">;数组最后一个元素索引Index</param>
private static void Sort(int[] numbers, int left, int right)
{
//左边索引小于右边,则还未排序完成
if (left < right)
{
//取中间的元素作为比较基准,小于他的往左边移,大于他的往右边移
int middle = numbers[(left + right) / 2];
//下标
int i = left - 1;
int j = right + 1;
while (true)
{
while (numbers[++i] < middle && i < right) ;
while (numbers[--j] > middle && j > 0) ;
if (i >= j)
break;
Swap(numbers, i, j);
}
//递归排,直到循环结束
Sort(numbers, left, i - 1);
Sort(numbers, j + 1, right);
}
}
/// <summary>
/// 交换元素值
/// </summary>
/// <param name="numbers">;数组</param>
/// <param name="i">;当前左边索引</param>
/// <param name="j">;当前右边索引</param>
private static void Swap(int[] numbers, int i, int j)
{
int number = numbers[i];
numbers[i] = numbers[j];
numbers[j] = number;
}
public static void Main()
{
//用随机数模拟的大数据量
int[] max = new int[80000];
//Random r = new Random(Guid.NewGuid().GetHashCode());
Random r = new Random(Environment.TickCount);
for (int i = 0; i < max.Length; i++)
{
max[i] = r.Next(0, 1000000);
}
//秒表掐时间
Stopwatch s = new Stopwatch();
s.Start();
Sort(max, 0, max.Length - 1);
//追加到集合里
StringBuilder temp = new StringBuilder();
for (int i = 0; i < max.Length; i++)
{
temp.Append(max[i].ToString() + ",");
}
s.Stop();
// Console.WriteLine(s.Elapsed);
Console.WriteLine(temp.ToString().Substring(0, temp.Length - 1));
Console.WriteLine(s.Elapsed);
Console.ReadLine();
}
}
}直观的理解快排,就是找中间量,比之大的放右边,比之小的放左边,递归下去直到所有的数据排完。
|