c#版快速排序

2008年01月27日 | 176 次浏览 | 学习  

copy了K*R《c程序设计语言》里面的实现。
using System;
using System.Collections.Generic;
using System.Text;

namespace LuceneTest
{
class Test
{
static void Main(string[] args)
{
int[] array = { 32, 45, 12, 18, 25, 60, 53, 78, 99, 83,21,8,10,33,24,66,80,23,18,95,61 };
qsort(ref array,0,array.Length-1);
for (int i = 0; i < array.Length; i++)
{
Console.WriteLine(array[i]);
}
Console.Read();

}
public static void qsort(ref int[] v, int left,int right)
{
int i, last;
if (left >= right) return;
swap(ref v, left, (left + right) / 2);//交换第一个和中间的一个,为什么取中间的一个,因为可能数组已经排好序了,这样就是最好的情况。这句的主要作用就是选取比较数。
last = left;//从左边开始一直到右边
for (i = left + 1; i <= right;i++ )
{
if (v[i] < v[left])//拿v[left]做比较数
swap(ref v,++last,i);//如果比左边的小则交换位置,last累计交换次数,交换了多少次就说明有多少数比v[left]小。
}
swap(ref v,left,last);//交换原来的位置,使得v[last]分别是左右两边的中间数
qsort(ref v,left,last-1);//往左递归
qsort(ref v,last+1,right);//往右递归
}
public static void swap(ref int[] v,int i,int j)
{
int temp;
temp = v[i];
v[i] = v[j];
v[j] = temp;
}
}
}

更新(2008年1月27日):另外写了一个Javascript版本的快速排序,思路和这个一样。地址:http://panweizeng.com/archives/123

评论

Comment RSS TrackBack URI

相关推荐:

发表评论

更多文章

最受欢迎

评论最多