第8天--算法(堆排序,基数排序)

1.堆排序

public class HeapSort {

  public void heapSort(int arr[]){
    for(int i = arr.length - 1;i >= 0;i --) {
      heapify(arr,i,arr.length);
    }
    int heapSize = arr.length;
    swap(arr,0,-- heapSize);
    while(heapSize > 0) {
      heapify(arr,0,heapSize);
      swap(arr,0,-- heapSize);
    }
  }
  public void heapify(int arr[],int index,int heapSize) {
    int left = 2 * index + 1;
    while(left < heapSize) {
      int max = left + 1 < heapSize && arr[left + 1] > arr[left] ? left + 1 : left;
      max = arr[index] > arr[max] ? index : max;
      if(max == index) {
        break;
      }
      swap(arr,index,max);
      index = max;
      left = 2 * index + 1;
    }
  }
  public void swap(int arr[],int x,int y) {
    int temp = arr[x];
    arr[x] = arr[y];
    arr[y] = temp;
  }
}

 

2.基数排序

public class RadixSort {
  public void radixSort(int arr[]) {
    if(arr == null || arr.length < 2) {
      return;
    }
    radixSort(arr,0,arr.length - 1,getmaxBit(arr));
  }
  public void radixSort(int arr[],int left,int right,int maxBit) {
    int help[] = new int[right - left + 1];
    for(int i = 1;i <= maxBit;i ++) {
      int count[] = new int[10];
      for(int j = left;j <= right;j ++) {
        int x = getFigure(arr[j],i);
        count[x] ++;
      }
      for(int j = 1;j < count.length;j ++) {
        count[j] = count[j] + count[j - 1];
      }
      for(int j = right;j >= left;j --) {
        int x = getFigure(arr[j],i);
        help[count[x] - 1] = arr[j];
        count[x] --;
      }
      for(int j = 0;j < help.length;j ++) {
        arr[left + j] = help[j];
      }
    }
  }
  public int getmaxBit(int arr[]) {
    int max = arr[0];
    for(int i = 1;i < arr.length;i ++) {
      max = Math.max(arr[i],max);
    }
    int res = 0;
    while(max != 0) {
      max /= 10;
      res ++;
    }
    return res;
  }
  public int getFigure(int x,int y) {
    return x / (int) Math.pow(10,(y - 1)) % 10;
  }
}

posted @ 2021-10-21 17:26  现在开始努力  阅读(35)  评论(0)    收藏  举报