An intuitive understanding of heapsort?

后端 未结 7 2207
春和景丽
春和景丽 2021-01-30 00:18

At school we are currently learning sorting algorithms in Java and I got for my homework the Heap Sort. I did my reading, I tried to find out as much as I could, but it seems I

7条回答
  •  终归单人心
    2021-01-30 00:55

    Heap sort include simplest logic with time complexity O(nlogn) and space complexity O(1)

     public class HeapSort {
    
    public static void main(String[] args) {
         Integer [] a={12,32,33,8,54,34,35,26,43,88,45};
    
         HeapS(a,a.length-1);
    
        System.out.println(Arrays.asList(a));
    
    }
    
    private static void HeapS(Integer[] a, int l) {
    
    
        if(l<=0)
            return;
    
        for (int i = l/2-1; i >=0 ; i--) {
    
            int index=a[2*i+1]>a[2*i+2]?2*i+1:2*i+2;
            if(a[index]>a[i]){
                int temp=a[index];
                a[index]=a[i];
                a[i]=temp;
            }
    
        }
        int temp=a[l];
        a[l]=a[0];
        a[0]=temp;
    
        HeapS(a,l-1);
    
      }
    }
    

提交回复
热议问题