分享一个C#实现的快速排序算法(转)
“算法” - 程序的灵魂! 这两天碰到一个需要处理排序的场景! 我第一印象想到的是"冒泡排序",由于效率不是特别友好基本上弃用,后来选择了有广大好评的快速排序方式,Google了一下,很多朋友都提出了自己的解 决方案,大致实现思路都是一样的!我也改写了一份C#的:
static ArrayList QuickSort(ArrayList arrayList) {
if (arrayList.Count <=1) return arrayList;
int pivotIndex = arrayList.Count /2;
int pivot = (int)arrayList[pivotIndex];
arrayList.Remove(pivot);
var left =new ArrayList();
var right =new ArrayList();
for (int i =0; i < arrayList.Count; i++) {
// 改变排序方式, 只要改变这里的比较方式
if ((int)arrayList[i] < pivot) {
left.Add(arrayList[i]);
} else {
right.Add(arrayList[i]);
}
}
var newArrayList = QuickSort(left);
newArrayList.Add(pivot);
newArrayList.AddRange(QuickSort(right));
return newArrayList;
}
if (arrayList.Count <=1) return arrayList;
int pivotIndex = arrayList.Count /2;
int pivot = (int)arrayList[pivotIndex];
arrayList.Remove(pivot);
var left =new ArrayList();
var right =new ArrayList();
for (int i =0; i < arrayList.Count; i++) {
// 改变排序方式, 只要改变这里的比较方式
if ((int)arrayList[i] < pivot) {
left.Add(arrayList[i]);
} else {
right.Add(arrayList[i]);
}
}
var newArrayList = QuickSort(left);
newArrayList.Add(pivot);
newArrayList.AddRange(QuickSort(right));
return newArrayList;
}
要想做个详细的了解, 可以参考阮先生的 快速排序(Quicksort)的Javascript实现
View Code
using System;
using System.Collections.Generic;
using System.Collections;
using System.Text;
namespace ConsoleApplication12
{
class Program
{
staticvoid Main(string[] args)
{
ArrayList at=new ArrayList();
int[] number=newint[]{5679,4,36,67976,124,235,453,436,6589,0,5,6,346,457,34,3642};
foreach(int i in number)
{
at.Add(i);
}
ArrayList al=QuickSort(at);
foreach (int j in al)
{
Console.WriteLine(j);
}
Console.ReadKey();
}
static ArrayList QuickSort(ArrayList arrayList)
{
if (arrayList.Count <=1) return arrayList;
int pivotIndex = arrayList.Count /2;
int pivot = (int)arrayList[pivotIndex];
arrayList.Remove(pivot);
ArrayList left =new ArrayList();
ArrayList right =new ArrayList();
for (int i =0; i < arrayList.Count; i++)
{
// 改变排序方式, 只要改变这里的比较方式
if ((int)arrayList[i] < pivot)
{
left.Add(arrayList[i]);
}
else
{
right.Add(arrayList[i]);
}
}
ArrayList newArrayList = QuickSort(left);
newArrayList.Add(pivot);
newArrayList.AddRange(QuickSort(right));
return newArrayList;
}
}
}