快速排序是对冒泡排序的一种改进。它基于分治策略,对于要排序的一个序列,从中选一值进行排序,将其放入到正确的位置position。然后以position为界,对左右两部分再分别做排序。直到划分的长度为1。具体实现如下:
代码
/// <summary>
/// 快速排序
/// </summary>
/// <param name="data"></param>
public static void QuickSort(int[] data)
{
if (data == null || data.Length < 1)
{
throw new ArgumentNullException("data");
}
Quick(data, 0, data.Length);
}
private static void Quick(int[] data, int low, int high)
{
if (data == null || data.Length < 1)
{
throw new ArgumentNullException("data");
}
if (low < 0 || low >= data.Length || high < 0 || high > data.Length)
{
return;
}
if (low < high)
{
int i = low, j = high, temp;
while (true)
{
do
{
i++;
} while (i < high && data[i] < data[low]);
do
{
j--;
} while (j > low && data[j] > data[low]);
if (i < j)
{
temp = data[i];
data[i] = data[j];
data[j] = temp;
}
else
{
temp = data[j];
data[j] = data[low];
data[low] = temp;
break;
}
}
Quick(data, low, j);
Quick(data, j + 1, high);
}
}
/// 快速排序
/// </summary>
/// <param name="data"></param>
public static void QuickSort(int[] data)
{
if (data == null || data.Length < 1)
{
throw new ArgumentNullException("data");
}
Quick(data, 0, data.Length);
}
private static void Quick(int[] data, int low, int high)
{
if (data == null || data.Length < 1)
{
throw new ArgumentNullException("data");
}
if (low < 0 || low >= data.Length || high < 0 || high > data.Length)
{
return;
}
if (low < high)
{
int i = low, j = high, temp;
while (true)
{
do
{
i++;
} while (i < high && data[i] < data[low]);
do
{
j--;
} while (j > low && data[j] > data[low]);
if (i < j)
{
temp = data[i];
data[i] = data[j];
data[j] = temp;
}
else
{
temp = data[j];
data[j] = data[low];
data[low] = temp;
break;
}
}
Quick(data, low, j);
Quick(data, j + 1, high);
}
}