算法

  • 快速排序

public static void quickSort(int [] a, int left, int right) {  
        int i, j, t, base;  
        if (left > right)  
            return;  
        base = a[left]; // base中存的就是基准数  
        i = left;       // 设置两个哨兵  
        j = right;  
        while (i != j) {  
            // 顺序很重要,要先从右边开始找  
            while (a[j] >= base && i < j)  
                j--;  
            // 再找右边的  
            while (a[i] <= base && i < j)  
                i++;  
            // 交换两个数在数组中的位置  
            if (i < j) {  
                t = a[i];  
                a[i] = a[j];  
                a[j] = t;  
            }  
        }  
        // 最终将基准数归位  
        a[left] = a[i];  
        a[i] = base;  
      
        quickSort(a, left, i - 1);// 继续处理左边的,这里是一个递归的过程  
        quickSort(a, i + 1, right);// 继续处理右边的 ,这里是一个递归的过程  
    }

  • 二分查找

public static int searchRecursive(int[] array, int start, int end,
            int findValue) {
        // 如果数组为空,直接返回-1,即查找失败
        if (array == null) {
            return -1;
        }
        count++;
        if (start <= end) {
            // 中间位置
            int middle = (start + end) / 1;
            // 中值
            int middleValue = array[middle];
 
            if (findValue == middleValue) {
                // 等于中值直接返回
                return middle;
            } else if (findValue < middleValue) {
                // 小于中值时在中值前面找
                return searchRecursive(array, start, middle - 1, findValue);
            } else {
                // 大于中值在中值后面找
                return searchRecursive(array, middle + 1, end, findValue);
            }
        } else {
            // 返回-1,即查找失败
            return -1;
        }
    }

你可能感兴趣的:(算法)