c#归并排序+快速排序

void MergeSort(int[] arr)
{
    int l = 0;
    int r = arr.Length-1;
    MergeSortSub(arr,l,r);
}
// 1,2
void MergeSortSub(int[] arr,int left,int right)
{
    if(left == right) return;
    int mid = left + ((right - left) >> 1);
    MergeSortSub(arr, left, mid);
    MergeSortSub(arr, mid+1, right);
    Merge(arr,left,mid,right);
}
// right也要传
void Merge(int[] arr,int left,int mid,int right){
    int[] help = new int[right-left+1];//*
    int i=0;
    int p1 = left;
    int p2 = mid+1;
    while(p1 <= mid && p2 <= right)
    {
        help[i++] = arr[p1] <= arr[p2] ? arr[p1++] : arr[p2++];
    }
    while(p1 <= mid)
    {
        help[i++] = arr[p1++];
    }
    while(p2 <= right)
    {
        help[i++] = arr[p2++];
    }
    for ( i = 0; i < help.Length; i++)
    {
        arr[left+i] = help[i]; // **
    }
}

----

void QuickSort2(int[] arr,int l,int r)
{
    if(l < r){
        SWAP(arr,l+(int)(new Random().NextDouble()*(r-l+1)),r);
        int[] p = Partition(arr,l,r);
        QuickSort2(arr,l,p[0]-1);
        QuickSort2(arr,p[1]+1,r);
    }
}
int[] Partition(int[] arr, int l, int r)
{
    int key = arr[r];
    int less = l - 1;
    int more = r;
    while (l < more)
    {
// l表示当前,arr[r]是划分值
if (arr[l] < arr[r]) // 当前数 < 划分值 { SWAP(arr, ++less, l++); } else if (arr[l] > arr[r]) { SWAP(arr, --more, l); } else { l++; } } SWAP(arr, more, r); return new int[] { less + 1, more }; }

 

posted @ 2023-05-03 10:01  vba是最好的语言  阅读(8)  评论(0编辑  收藏  举报