Heap sort implementation

  When Besides heap sort, we first talk about what is heap big top, top small heap.

  The so-called Big Top heap, the first is a binary tree. Then to the left child node and the right child nodes are smaller than their parent. The top small heap just the opposite.  

  Obviously to get the data, we first turn data into heap big top. Code:

void adjust(int arr[],int i,int length)
{
    int temp = arr[i];
    
    for(int k = 2 * i + 1; k < length; k = 2 * k + 1)
    {
        
        if(k + 1 < length && arr[k] < arr[k+1])
        {
            k++;
        } 
        if(arr[k] > temp)
        {
            arr[i] = arr[k];
            i = k;
        }else{
            
            break;
        }
        arr[i] = temp;
    }
}

  arr array is to be converted. Node i is the length you want you to operate the operating length of the array.

  Lined up after the big top of the heap root discharged last. This operation will certainly upset the big top heap. Once again, we just turned the big top heap ok. Code:

void sort(int arr[],int length)
{
    for(int i = length / 2 - 1; i >= 0; i--)
    {
        adjust(arr,i,length);
    }
    
    
    for(int j = length - 1; j > 0; j--)
    {
        int temp = arr[j];
        arr[j] = arr[0];
        arr[0] = temp;
        
        adjust(arr,0,j);
    }
}

  The whole process just fine. Here explain: adjust the parameter calculated i: i = arr.length / 2 -1

Guess you like

Origin www.cnblogs.com/zdybj/p/12424217.html