须知的C#常用的排序方法Word格式文档下载.docx
《须知的C#常用的排序方法Word格式文档下载.docx》由会员分享,可在线阅读,更多相关《须知的C#常用的排序方法Word格式文档下载.docx(12页珍藏版)》请在冰豆网上搜索。
int[]array=newint[]{6,6,5,4,3,2,1,0};
array=Sort(array);
foreach(variteminarray)
Console.WriteLine(item.ToString());
}
Console.ReadKey();
staticint[]Sort(int[]array)
for(inti=0;
i<
array.Length;
i++)
for(intj=0;
j<
array.Length-i-1;
j++)
if(array[j+1]<
array[j])
Swap(array,j,j+1);
returnarray;
staticvoidSwap(int[]array,intfirstIndex,intsecondIndex)
intpreserve=array[firstIndex];
array[firstIndex]=array[secondIndex];
array[secondIndex]=preserve;
4.2简单选择排序
array=SelectSort(array);
staticint[]SelectSort(int[]array)
for(intj=i;
if(array[j]<
array[i])
Swap(array,j,i);
4.3快速排序
array=QuickSort(array,0,array.Length-1);
staticint[]QuickSort(int[]array,intstart,intend)
intlow=start;
inthigh=end;
intmark=start;
while(low<
high)
mark)
if(array[low]>
array[mark])
Swap(array,low,mark);
mark=low;
continue;
else
low++;
while(mark<
if(array[mark]>
array[high])
Swap(array,high,mark);
mark=high;
high--;
if(mark-start>
1)
QuickSort(array,start,mark-1);
if(end-mark>
QuickSort(array,mark+1,end);
4.4堆排序
int[]array=newint[]{5,6,7,8,2,3,4,6,5,4,3,2};
array=HeapSort(array);
publicstaticvoidCreateHeap(int[]array,intlastIndex)
for(inti=lastIndex;
i>
0;
i--)
if(array[i]>
array[i/2])
Swap(array,i,i/2);
publicstaticint[]HeapSort(int[]array)
for(inti=array.Length-1;
CreateHeap(array,i);
Swap(array,0,i);
4.5二分插入排序
int[]array=newint[]{3,2,1,4,5,67,678678,234234,2,3,4,5,6,7,8,4};
array=HalfInsertSort(array);
publicstaticint[]HalfInsertSort(int[]array)
intstart=0;
intend=i-1;
while(start<
=end)
intmiddle=(start+end)/2;
if(array[middle]<
=array[i])
start=middle+1;
end=middle-1;
intinsertValue=array[i];
j>
start;
j--)
array[j]=array[j-1];
array[start]=insertValue;
4.6直接插入排序
array=InsertSort(array);
staticint[]InsertSort(int[]array)
i;
if(array[j]>
4.7归并排序
int[]array=newint[]{1,1,2,2,2,2,3,3,2,2,2,22222222,1,1,1,1,1,1,1,1,0,0,0,0,7};
array=MergeSort(array,0,array.Length-1);
publicstaticint[]MergeSort(int[]array,intstart,intend)
intmiddle=start;
if(start<
end)
middle=(start+end)/2;
MergeSort(array,start,middle);
MergeSort(array,middle+1,end);
Merge(array,start,end);
publicstaticvoidMerge(int[]array,intstart,intend)
Queue<
int>
container=newQueue<
();
intfirst=start;
intsecond=middle+1;
while(first<
=middle&
&
second<
if(array[first]<
array[second])
container.Enqueue(array[first++]);
container.Enqueue(array[second++]);
=middle)
while(second<
for(inti=start;
=end;
array[i]=container.Dequeue();
4.8希尔排序
int[]array=newint[]{3,2,1,4,5,67,678678,234234,31231,1,3,3,3,3,3,3,3,3,2,2,2,1,1,1,1,1,1,12,3,3,3,3,32,3,4,5,6,7,8,4};
foreach(variteminShellSort(array))
publicstaticint[]ShellSort(int[]array)
intpoint=array.Length/2;
while(point>
0)
point;
i++)
j+=point)
for(intk=i;
k<
j;
k+=point)
if(array[k]>
array[j])
intinsertValue=array[j];
for(intt=j;
t>
k;
t-=point)
array[t]=array[t-point];
array[k]=insertValue;
point=point/2;