Code
using System;
using System.Collections.Generic;
using System.Text;
namespace SortAlgorithm
{
class QuickSort
{
static void Main()
{
int[] A ={ 10, 1, 2, 12, 34, 23, 56, 67, 4, 11 }; //基本思想是:第一轮比较,把最小的数弄到最前面,其实现是两个数通过交换位置。
QuickSort quick = new QuickSort();
quick.Sort(A, 0, 9);
for (int m = 0; m < A.Length; m++)
Console.Write("{0} ", A[m]);
Console.Read();
}
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];
}
}
}
using System;
using System.Collections.Generic;
using System.Text;
namespace SortAlgorithm
{
class QuickSort
{
static void Main()
{
int[] A ={ 10, 1, 2, 12, 34, 23, 56, 67, 4, 11 }; //基本思想是:第一轮比较,把最小的数弄到最前面,其实现是两个数通过交换位置。
QuickSort quick = new QuickSort();
quick.Sort(A, 0, 9);
for (int m = 0; m < A.Length; m++)
Console.Write("{0} ", A[m]);
Console.Read();
}
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];
}
}
}