查找算法

1)查找第N小的值
2)查找最小最大值

#!/usr/bin/env python3.3
# -*- coding:utf-8 -*-
# Copyright 2013

def randomized_select(data, n):
    if n > 0 and n <= len(data):
        left, right = 0, len(data) - 1
        pivot_index = partition(data, left, right)
        while pivot_index != n - 1: 
            if pivot_index < n - 1:
                left = pivot_index + 1
            else:
                right = pivot_index - 1
            pivot_index = partition(data, left, right)
        return data[pivot_index]

def min_max_select(data): if len(data) > 0: min_value = max_value = data[0] start_pos = 0 if len(data) % 2 == 0 else 1 for i in range(start_pos, len(data)-1, 2): if data[i] < data[i+1]: if data[i] < min_value: min_value = data[i] if data[i+1] > max_value: max_value = data[i+1] else: if data[i+1] < min_value: min_value = data[i+1] if data[i] > max_value: max_value = data[i] return min_value, max_value
posted @ 2013-03-25 20:10  Leung文  阅读(178)  评论(0编辑  收藏  举报