Algorithm 3_Quick_Sort
来源:互联网 发布:已备案域名出售 编辑:程序博客网 时间:2024/06/08 03:51
Choose an index named middleIndex between fist Index and last index of an array which is to be sort.We can get a rearranged array that has the following jfeatures: all elements from first index to middle index is smaller than array[middleindex];all elements from middle index to last index is larger than array[middleindex].The Partition method return the middle index so we can rearrange the two subarray by the same way.
Let’s show it.
private void Swap(Int32[] arr, Int32 firstIndex, Int32 secondIndex)
{
if (firstIndex < arr.Length && secondIndex < arr.Length)
{
Int32 temp = arr[firstIndex];
arr[firstIndex] = arr[secondIndex];
arr[secondIndex] = temp;
}
}
//In this method,we use arr[lastIndex] as the middleValue
private Int32 Partition(Int32[] arr, Int32 firstIndex, Int32 lastIndex)
{
if (firstIndex < arr.Length && lastIndex < arr.Length)
{
Int32 middleValue = arr[lastIndex];
Int32 i = firstIndex - 1;
for (Int32 j = firstIndex; j < lastIndex; j++)
{
if (arr[j] <= middleValue)
Swap(arr, ++i, j);
}
Swap(arr, i + 1, lastIndex);
return i + 1;
}
else
{
return -1;
}
}
public void Sort(Int32[] arr, Int32 firstIndex, Int32 lastIndex)
{
if (firstIndex < lastIndex)
{
Int32 middleIndex = Partition(arr, firstIndex, lastIndex);
Sort(arr, firstIndex, middleIndex - 1);
Sort(arr, middleIndex + 1, lastIndex);
}
}
Ok,it fine.
Let's make a random index between firstIndex and lastIndex,Choose arr[randomIndex] as the middleValue
{
Random randomer = new Random();
Int32 index = randomer.Next(firstIndex, lastIndex);
Swap(arr, index, lastIndex);
return Partition(arr, firstIndex, lastIndex);
}
public void RandomizedSort(Int32[] arr, Int32 firstIndex, Int32 lastIndex)
{
if (firstIndex < lastIndex)
{
Int32 middleIndex = RandomizedPartition(arr, firstIndex, lastIndex);
RandomizedSort(arr, firstIndex, middleIndex - 1);
RandomizedSort(arr, middleIndex + 1, lastIndex);
}
}
the worst-case running time of QuickSort is big theta n*n on an input array of n numbers.
But the quicksort is often the best practical choice for sorting because it is efficient in the average:its expected running time is big theta n*lgn.
- Algorithm 3_Quick_Sort
- 排序_Quick_Sort(快速排序)
- 快速排序_quick_sort
- 分治_递归_quick_sort
- [c++,algorithm]3_fpTree
- Smarking Algorithm Contest 3
- Parallel&Distributed Algorithm-3
- Algorithm
- Algorithm
- algorithm
- algorithm
- algorithm
- algorithm
- algorithm
- Algorithm
- Algorithm
- algorithm
- Algorithm
- PHP专业项目实例开发
- 在线查询大全
- allowDefinition='MachineToApplication' 的节是错误的
- No MFC 编程01 - 最精简的 win32 程序_编程
- C#获取汉字的区位码的方法
- Algorithm 3_Quick_Sort
- Use C# and the .NET Framework to develop your own plugin architecture
- Maven2快速入门教程
- Binary Serialization and BinaryFormatter with WebServices
- 在PowerDesigner12.5下做Oracle9i2的反向工程
- JAVA split 用法
- Java在不同环境下获取当前路径的方法
- Hibernate简单配置
- 将txt文件和excel文件导入SQL2000数据库