zoukankan      html  css  js  c++  java
  • Java常用排序算法

    一、冒泡排序

    public static void bubblesort(int[] a){
        for(int i=a.length;i>0;i--){
            for(int j=1;j<i;j++){
                if(a[j]<a[j-1]){
                    int tmp = a[j];
                    a[j] = a[j-1];
                    a[j-1] =tmp;
                }
            }
        }
    }

    二、选择排序

    public static void selectsort(int[] a){
        int t = 0;
        for(int i=0;i<a.length;i++){
            int tmp = i;
            for(int j=i+1;j<a.length;j++){
                if(a[j]<a[tmp]){
                    tmp =j;
                }
            }
            t = a[tmp];
            a[tmp] = a[i];
            a[i] = t;
        }
        
    }

    三、插入排序

    public static void insertsort(int[] a){
        for(int i=1;i<a.length;i++){
            for(int j=i;j>0 && a[j]<a[j-1];j--){
                int t = a[j];
                a[j] = a[j-1];
                a[j-1] = t;
            }
        }
    }

    四、快速排序

    public static void quicksort(int[] a, int left, int right) {
        if(left<right){
            int key = a[left];
            int low = left;
            int high = right;
            while(low<high){
                while(low<high && a[high]>=key){
                    high--;
                }
                a[low] = a[high];
                while(low<high && a[low]<=key){
                    low++;
                }
                a[high] = a[low];
            }
            a[low] = key;
            quicksort(a, left, low -1);
            quicksort(a, low + 1, right);
        }
    }
  • 相关阅读:
    N-Queens
    Pow(x, n)
    Maximum Subarray
    Spiral Matrix
    Jump Game
    Merge Intervals
    Insert Interval
    Length of Last Word
    Spiral Matrix II
    Amazon 面经
  • 原文地址:https://www.cnblogs.com/tianyuchen/p/6644611.html
Copyright © 2011-2022 走看看