几种简单的排序

花了些时间复习了下排序,记录来吧,权当巩固之用~

using System;
class sort
{
static void Main()
{
var arr
= IntiArray();
BubbleSort(arr);
arr
= IntiArray();
insertSort(arr);
arr
= IntiArray();
SimpleSelectSort(arr);
arr
= IntiArray();
QucikSort(arr,
0, arr.Length - 1);
}
public static int[] IntiArray()
{
Random ran
= new Random();
int[] arr = new int[10];
for (int i = 0; i < 10;i++ )
{
arr[i]
= ran.Next(1, 100);
}
return arr;
}
public static int[] BubbleSort(int[] arr)
{
int i, j;
for (i = 0, j = arr.Length; i < j;i++ )
{
bool flag = false;
for (int k = j-1; k > i;k--)//index一定要对好
{
if(arr[k]<arr[k-1])
{
int temp = arr[k - 1];
arr[k
- 1] = arr[k];
arr[k]
= temp;
flag
= true;//注意此处要变化flag
}
}
if(!flag)
{
return arr;
}
}
return arr;
}
public static int[] insertSort(int[] arr)
{
for (int i = 0, j = arr.Length; i < j-1;i++ )
{
int temp = arr[i + 1];
int k = i;
while (k >= 0 && temp < arr[k])
{
arr[k
+ 1] = arr[k];
k
--;
}
arr[k
+ 1] = temp;
}
return arr;
}
public static int[] SimpleSelectSort(int[] arr)
{
for (int i = 0, j = arr.Length; i < j;i++ )
{
int t = i;
for (int k = i + 1; k < j;k++ )
{
if(arr[t]>arr[k])
{
t
= k;//最小的下标保存在t中
}
}
int temp = arr[i];
arr[i]
= arr[t];
arr[t]
= temp;
}
return arr;
}
public static int Partition(int[] array,int low,int high)
{
int i = low;
int j = high;
int pivot = array[low];
while(low<high)
{
while(low<high&&array[high]>pivot)
{
--high;
}
array[low]
= array[high];
while(low<high&&array[low]<pivot)
{
++low;
}
array[high]
= array[low];
}
array[low]
= pivot;
return low;
}
public static int[] QucikSort(int[] array,int low,int high)
{
if(low<high)
{
int pivotKey = Partition(array,low,high);
QucikSort(array, low, pivotKey
- 1);
QucikSort(array, pivotKey
+ 1, high);
}
return array;
}

}

 

 

 

posted @ 2010-03-23 18:08  Tmac_  阅读(202)  评论(0编辑  收藏  举报