# 快速排序非递归c#实现

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace 快速排序
{
class Program
{
//自己写的方法
public static void change(ref int a, ref int b)
{
int temp = b;
b = a;
a = temp;
}
public static int[] KSsort(int[] a, int start, int end)
{
bool flag = true;
while (end != start)
{
if (flag)
{
int tempend = a.Length - 1;
while (start < tempend)
{
if (a[start] > a[tempend])//右侧找比自己小的数
{
change(ref a[start],ref a[tempend]);
flag = false;
break;
}
else
{
tempend--;
if (start == tempend)
{
start++;
flag = false;
}
}
}
}
else
{
int tempstart = 0;
while (tempstart < end)
{
if (a[tempstart] > a[end])//左侧找比自己大的数
{
change(ref a[tempstart], ref a[end]);
flag = true;
break;
}
else
{
tempstart++;
if (tempstart == end)
{
end--;
flag = true;
}
}
}
}
}
return a;
}

static void Main(string[] args)
{
int[] array = new int[1000];
Random rand = new Random();
for (int i = 0; i < array.Length; i++)
{
array[i] = rand.Next(1001);
}
Console.WriteLine("原始数据");
foreach (var item in array)
{
Console.Write(item + "  ");
}
Console.WriteLine();

Console.WriteLine();

int starttime = DateTime.Now.Millisecond;
int[] result = KSsort(array, 0, array.Length - 1);
foreach (var item in result)
{
Console.Write(item + "  ");
}
Console.WriteLine("排序耗时 " + (DateTime.Now.Millisecond - starttime));
Console.ReadLine();
}
}
}

07-02 2858

09-14 1293

09-01 2148

05-06 4367

03-20 1119

09-26 2.6万

04-06 2683

11-29 6248

04-27 934

01-09 2620