快速排序(QuickSort)用C# 实现的小例子
class QuickSort
{
public void Sort(int[] data, int start, int end)
{
if (start >= end) return;
if (start + 1 == end)
{
if (data[start] > data[end])
Swap(data, start, end);
return;
}
int indexL = start + 1, indexR = end;
while (indexL < indexR)
{
// Get from left
while (indexL <= end && data[start] >= data[indexL])
indexL++;
// Get from right
while (indexR > start && data[start] < data[indexR])
indexR--;
if (indexL < indexR)
{
Swap(data, indexR, indexL);
}
}
if(indexL-1 !=start)
Swap(data, start, indexL - 1);
Sort(data, start, indexL - 2);
Sort(data, indexL, end);
}
private void Swap(int[] data, int x, int y)
{
data[x] = data[x] + data[y];
data[y] = data[x] - data[y];
data[x] = data[x] - data[y];
}
}
{
public void Sort(int[] data, int start, int end)
{
if (start >= end) return;
if (start + 1 == end)
{
if (data[start] > data[end])
Swap(data, start, end);
return;
}
int indexL = start + 1, indexR = end;
while (indexL < indexR)
{
// Get from left
while (indexL <= end && data[start] >= data[indexL])
indexL++;
// Get from right
while (indexR > start && data[start] < data[indexR])
indexR--;
if (indexL < indexR)
{
Swap(data, indexR, indexL);
}
}
if(indexL-1 !=start)
Swap(data, start, indexL - 1);
Sort(data, start, indexL - 2);
Sort(data, indexL, end);
}
private void Swap(int[] data, int x, int y)
{
data[x] = data[x] + data[y];
data[y] = data[x] - data[y];
data[x] = data[x] - data[y];
}
}