您的位置:首页 > 其它

快速排序,冒泡排序,插入排序 完整示例

2011-07-15 10:19 330 查看
快速排序
using System;
using System.Collections.Generic;
using System.Collections;
using System.Text;
namespace ConsoleApplication12
{
class Program
{
static void Main(string[] args)
{
ArrayList at = new ArrayList();
int[] number = new int[] { 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;
}
}
}

冒泡排序
using System;
using System.Collections.Generic;
using System.Collections;
using System.Text;
namespace ConsoleApplication12
{
class Program
{
static void Main(string[] args)
{
int[] number=new int[]{5679,4,36,67976,124,235,453,436,6589,0,5,6,346,457,34,3642};
QuickSort(ref number);
foreach (int j in number)
{
Console.WriteLine(j);
}
Console.ReadKey();
}
static void QuickSort(ref int[] number)
{
for (int i = 0; i < number.Length; i++)
{
// 改变排序方式, 只要改变这里的比较方式
for (int j = 0; j < number.Length - i-1; j++)
{
if (number[j]>number[j+1])
{
int temp = number[j];
number[j] = number[j + 1];
number[j + 1] = temp;
}
}
}
}
}
}

插入排序
using System;
using System.Collections.Generic;
using System.Collections;
using System.Text;
namespace ConsoleApplication12
{
class Program
{
static void Main(string[] args)
{
int[] number=new int[]{5679,4,36,67976,124,235,453,436,6589,0,5,6,346,457,34,3642};
QuickSort(ref number);
foreach (int j in number)
{
Console.WriteLine(j);
}
Console.ReadKey();
}
static void QuickSort(ref int[] number)
{
for (int i = 1; i < number.Length; i++)
{
int temp = number[i];
int j=i;
while (j>0 &&number[j-1]>temp)
{
number[j] = number[j-1];
--j;
}
number[j] = temp;
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐