张银的博客


Eat to live, but do not live to eat.

导航

快速排序代码

Posted on 2012-04-08 23:50  张银  阅读(635)  评论(0编辑  收藏  举报
using System;
using System.Collections.Generic;
using System.Text;
namespace temp
{
public class QuickSort  
{
/// <summary>  
/// 排序
/// </summary>   
/// <param name="numbers">待排序数组</param>  
/// <param name="left">数组第一个元素索引Index</param>   
/// <param name="right">数组最后一个元素索引Index</param>   
private static void Sort(int[] numbers,int left,int right)   
{   
//左边索引小于右边,则还未排序完成   
if (left < right)   
{   
//取中间的元素作为比较基准,小于他的往左边移,大于他的往右边移   
int middle = numbers[(left + right) / 2];   
int i = left - 1;   
int j = right + 1;
while (true)   
{
while (numbers[++i] < middle && i < right)
{ ;}
while (numbers[--j] > middle && j > 0)
{ ;}
if (i >= j) break;
Swap(numbers,i,j);
}   
Sort(numbers,left,i - 1);  
Sort(numbers,j + 1,right);  
}   
}   
/// <summary>   
/// 交换元素值   
/// </summary>   
/// <param name="numbers">数组</param>   
/// <param name="i">当前左边索引</param>   
/// <param name="j">当前右边索引</param>   
private static void Swap(int[] numbers,int i,int j)  
{   
int number = numbers[i];  
numbers[i] = numbers[j];   
numbers[j] = number;
}  
public static void Main()  
{  
int[] arr = { 6,5,2,9,7,4,0,-1,-4,-2,3,2,0,9 };  
Sort(arr, 0, arr.Length-1);  
StringBuilder temp = new StringBuilder();
for (int i = 0; i <= arr.Length-1; i++)  
{  
temp.Append(arr[i].ToString()+",");
}  
Console.WriteLine(temp.ToString().Substring(0, temp.Length-1));  
Console.ReadLine();  
}  
}  
}