Combine QuickSort and Median selection algorithm

前端 未结 4 704
隐瞒了意图╮
隐瞒了意图╮ 2021-01-25 15:18

I want to modify QuickSort (in Java) so that every time Partition is called, the median of the proportioned array is used as the pivot.

I have a median selection algorit

相关标签:
4条回答
  • 2021-01-25 15:55

    You can use this ...

    int Select(int array[],int start, int end,int k){
    
    if(start==end){
        return start;
    }
    
    int x=array[end];
    int i=start-1;
    for(int j=start;j<=end-1;j++){
        if(array[j]<x){
            i++;
            Swap(array+i,array+j);
        }
    }
    i++;
    Swap(array+i,array+end);
    
    if(i==k){
        return i;
    }
    else if(i>k){
        return Select(array,start,i-1,k);
    }
    else{
        return Select(array,i+1,end,k);
    }
    

    }

    Select will partition array on kth smallest element in array;

    0 讨论(0)
  • 2021-01-25 16:04

    What you are looking for is the Selection Algorithm. Here's a link with pseudocode.

    From the link:

    In computer science, a selection algorithm is an algorithm for finding the kth smallest number in a list

    To find the median you want to find the k=floor((n+1)/2) smallest number in the list where n is the size of the list.

    0 讨论(0)
  • 2021-01-25 16:20

    The standard way to get the median is to sort the data. And you want to sort the data by partitioning on the median. This seems very chicken and egg to me.

    Could you elaborate on why you want to partition/pivot on the median?

    0 讨论(0)
  • 2021-01-25 16:20

    Note that in PARTITION the pivot is A[r].

    public int QUICKSORT2(int[] A, int p, int r) {
        if (p<r) {
            int median=Math.floor((p + r) /2) - p + 1
            int q=SELECT(A, p, r, median)
            q=PARTITION2(A, p, r, q)
            QUICKSORT2(A, p, q-1)
            QUICKSORT2(A, q+1, r)
        }
    }
    
    public int PARTITION2(int[]A, int p, int r, int q) {
        int temp = A[r];
        A[r]=A[q];
        A[q]=temp;
        return PARTITION(A, p, r)
    }
    
    0 讨论(0)
提交回复
热议问题