【排序】Sort Colors

排序

解法一:快排,递归实现

public class Solution {
    
    public void qsort(int [] num, int low, int high){
        int i = low, j=high;
        
        if(low >= high) return ;
        
        while(low < high){
            //
            while(low < high && num[high] >= num[i]) high--;
            while(low < high && num[low] <= num[i]) low++;
            
            int temp = num[high];
            num[high] = num[low];
            num[low] = temp;
        }
        int temp = num[low];
        num[low] = num[i];
        num[i] = temp;
        qsort(num, i, low-1);
        qsort(num, low+1, j);
    }
    
    public void sortColors(int[] A) {
        qsort(A, 0, A.length-1);
    }
}

解法二:归并排序,递归实现

public class Solution {
    
    public void mergesort(int[] num, int low, int high){
        if(low >= high) return;
        
        int mid = (low + high) / 2;
        mergesort(num, low, mid);
        mergesort(num, mid+1, high);
        //
        int k,i, j, b[] = new int[mid-low+1], c[] = new int[high-mid];
        for(i=0,j=low; j<=mid; j++, i++){
            b[i] = num[j];
        }
        for(i=0, j=mid+1; j<=high; j++,i++){
            c[i] = num[j];
        }
        
        i=0;
        j=0;
        for(k=low; i<b.length&&j<c.length; k++){
            if(b[i] >= c[j]) num[k] = c[j++];
            else num[k] = b[i++];
        }
        
        while(i < b.length) num[k++] = b[i++];
        while(j < c.length) num[k++] = c[j++];
    }
    
    public void sortColors(int[] A) {
        mergesort(A, 0, A.length-1);
    }
}
解法三:堆排序
public class Solution {
    
    public void exchange(int []a, int i, int j){
        int temp = a[i];
        a[i] = a[j];
        a[j] = temp;
    }
    
    public void heapify(int [] a, int pos, int size){
        int l = pos*2 + 1;
        int r = l + 1;
        int largest = pos;
        if(l <= size && a[l] > a[largest])
        largest = l;
        if(r <= size && a[r] > a[largest])
        largest = r;
        
        if(largest != pos){
            exchange(a, pos, largest);
            heapify(a, largest, size);
        }
    }
    
    public void buildHeap(int [] a, int size){
        for(int i=(size-1)/2; i>=0; i--){
            heapify(a, i, size);
        }
    }
    
    public void heapSort(int [] a){
        int size = a.length-1;
        buildHeap(a, size);
        
        for(int i=a.length-1; i>0; i--){
            exchange(a, 0, i);
            size--;
            heapify(a, 0, size);
        }
    }
    
    public void sortColors(int[] A) {
        heapSort(A);
    }
}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值