经典算法:选择排序、冒泡排序、二分查找

选择排序:


$arr[$j]){
                                $temp = $arr[$i];
                                $arr[$i] = $arr[$j];
                                $arr[$j] = $temp;
                        }
                }
        }
        var_dump($arr);
?>




冒泡排序:


$arr[$j+1]){
                                $temp = $arr[$j];
                                $arr[$j] = $arr[$j+1];
                                $arr[$j+1] = $temp;
                        }
                }
        }
        var_dump($arr);
?>


$arr[$j]){
                                $temp = $arr[$i];
                                $arr[$i] = $arr[$j];
                                $arr[$j] = $temp;
                        }
                }
        }
        var_dump($arr);
?>


java实现二分查找法:

/**
 *二分查找普通实现。
 * @param srcArray有序数组
 * @param key查找元素
 * @return 不存在返回-1
 */
public static int binSearch(int srcArray[], int key) {
    int mid = srcArray.length / 2;
    if (key == srcArray[mid]) {
        return mid;
    }

    int start = 0;
    int end = srcArray.length - 1;
    while (start <= end) {
        mid = (end - start) / 2 + start;
        if (key < srcArray[mid]) {
            end = mid - 1;
        } else if (key > srcArray[mid]) {
            start = mid + 1;
        } else {
            return mid;
        }
    }
    return -1;
}



/**
 *二分查找普通实现。
 * @param srcArray有序数组
 * @param key查找元素
 * @return 不存在返回-1
 */
public static int binSearch(int srcArray[], int key) {
    int mid = srcArray.length / 2;
    if (key == srcArray[mid]) {
        return mid;
    }

    int start = 0;
    int end = srcArray.length - 1;
    while (start <= end) {
        mid = (end - start) / 2 + start;
        if (key < srcArray[mid]) {
            end = mid - 1;
        } else if (key > srcArray[mid]) {
            start = mid + 1;
        } else {
            return mid;
        }
    }
    return -1;
}



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