快速排序算法

时间:2022-07-31 09:46:08

 

今天在网上看了一下传说中的快速排序,然后试着用C#递归实现了一下:(这里是降序)

void
Main(){
int[] arraytosort=new []{1,1,2,3,5,6,7,70,10,58,3,19,1,0,5,2,4,3};

Helper helper
=new Helper();
var result=helper.SplitArray(arraytosort);
string show=string.Join(",",result.Select(r=>r.ToString()).ToArray());
Console.WriteLine(show);
}
public class Helper{
public int[] SplitArray(int[] array){
string show=string.Join(",",array.Select(r=>r.ToString()).ToArray());
Console.WriteLine(
"最初数组:"+show);
if(array.Length<=1){
return array;
}
int position=array.Length/2;
var valueP=array[position];
array[position]
=array[0];
array[
0]=valueP;
show
=string.Join(",",array.Select(r=>r.ToString()).ToArray());
Console.WriteLine(
"第一次手动换结果:"+show);
int comparePosition=0;
for(int i=comparePosition+1;i<array.Length;i++){
Console.WriteLine(
"此时用来比较的基准值为:"+array[comparePosition]+"基准值下标comparePosition为:"+comparePosition+"/比较值为:"+array[i]+"比较值下标i为"+i);
if(array[comparePosition]<array[i]){
Console.WriteLine(
"基准值小于比较值换位置");
var tempValue=array[i];
for(int j=i;j>comparePosition;j--){
array[j]
=array[j-1];
}
array[comparePosition]
=tempValue;
comparePosition
=comparePosition+1;
show
=string.Join(",",array.Select(r=>r.ToString()).ToArray());
Console.WriteLine(
"换位置后结果:"+show);
}
else{
Console.WriteLine(
"基准值大于或等于比较值不换位置");
}
}
show
=string.Join(",",array.Select(r=>r.ToString()).ToArray());
Console.WriteLine(
"分组结果比基准值大的"+show+ " 此时comparePosition:"+comparePosition);
int[] arraySmall=new int[array.Length-1-comparePosition];
Console.WriteLine(
"arraySmall的length为:"+arraySmall.Length);
int[] arrayLarge=new int[comparePosition];
if(arrayLarge.Length>0){
for(int i=0;i<arrayLarge.Length;i++){
arrayLarge[i]
=array[i];
}
}
if(arraySmall.Length>0){
for(int i=0;i<arraySmall.Length;i++){
arraySmall[i]
=array[comparePosition+1+i];
Console.WriteLine(
"arraySmall的i为:"+arraySmall[i]);
}
}
var arrayLeft=SplitArray(arrayLarge);
var arrayRight=SplitArray(arraySmall);
var result=new int[array.Length];
Array.Copy(arrayLeft,
0,result,0,arrayLeft.Length);
result[arrayLeft.Length]
=valueP;
Array.Copy(arrayRight,
0,result,arrayLeft.Length+1,arrayRight.Length);
return result;
}
果然自己还是菜,调试了半天才调通,不知道用LIST是不是更好点