悠然哈哈哈

导航

java 排序算法

//冒泡
public static void bubbleSort(int[] numbers) {   
    int temp; // 记录临时中间值   
    int size = numbers.length; // 数组大小   
    for (int i = 0; i < size - 1; i++) {   
        for (int j = i + 1; j < size; j++) {   
            if (numbers[i] < numbers[j]) { // 交换两数的位置   
                temp = numbers[i];   
                numbers[i] = numbers[j];   
                numbers[j] = temp;   
            }   
        }   
    }   
}  

 

//快速排序
public static void quickSort(int[] numbers, int start, int end) {   
    if (start < end) {   
        int base = numbers[start]; // 选定的基准值(第一个数值作为基准值)   
        int temp; // 记录临时中间值   
        int i = start, j = end;   
        do {   
            while ((numbers[i] < base) && (i < end))   
                i++;   
            while ((numbers[j] > base) && (j > start))   
                j--;   
            if (i <= j) {   
                temp = numbers[i];   
                numbers[i] = numbers[j];   
                numbers[j] = temp;   
                i++;   
                j--;   
            }   
        } while (i <= j);   
        if (start < j)   
            quickSort(numbers, start, j);   
        if (end > i)   
            quickSort(numbers, i, end);   
    }   
}  

 

//选择

public static void selectSort(int[] numbers) {   
    int size = numbers.length, temp;   
    for (int i = 0; i < size; i++) {   
        int k = i;   
        for (int j = size - 1; j >i; j--)  {   
            if (numbers[j] < numbers[k])  k = j;   
        }   
        temp = numbers[i];   
        numbers[i] = numbers[k];   
        numbers[k] = temp;   
    }   
}  

 

//插入
public static void insertSort(int[] numbers) {   
    int size = numbers.length, temp, j;   
    for(int i=1; i<size; i++) {   
        temp = numbers[i];   
        for(j = i; j > 0 && temp < numbers[j-1]; j--)   
            numbers[j] = numbers[j-1];   
        numbers[j] = temp;   
    }   
}  

 

posted on 2016-02-18 13:42  悠然886  阅读(211)  评论(0编辑  收藏  举报