带有交换计数的Python冒泡排序列表

时间:2014-10-15 11:17:48

标签: python sorting

我试图创建一个使用冒泡排序对列表进行排序的函数,并返回一个包含交换次数和比较次数的元组。这样:

print(perform_bubble_sort([3, 5, 7]))    
>>> (3, 0)


我尝试使用以下代码,但由于某种原因它没有返回正确数量的比较。

def perform_bubble_sort(blist):
    cmpcount, swapcount = 0, 0
    while True:
        swapped = False
        for i in range(1, len(blist)):
            cmpcount += 1
            if blist[i-1] > blist[i]:
                swapcount += 1
                blist[i-1], blist[i] = blist[i], blist[i-1]
                swapped = True
        if not swapped:
            break
    return cmpcount, swapcount

2 个答案:

答案 0 :(得分:3)

def perform_bubble_sort(blist):
    cmpcount, swapcount = 0, 0
    for j in range(len(blist)):
        for i in range(1, len(blist)-j):
            cmpcount += 1
            if blist[i-1] > blist[i]:
                swapcount += 1
                blist[i-1], blist[i] = blist[i], blist[i-1]
    return cmpcount, swapcount

您不需要每次迭代blist

答案 1 :(得分:0)

public void getText(String name) throws IOException  {

    try{
        WebDriverWait wait=new WebDriverWait(driver,20);
        wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[@id='mid']/div")));
        WebElement result=driver.findElement(By.id("mid"));
        Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(name), "utf-8"));
        writer.write(result.getText());
        writer.close();
    }catch (TimeoutException e){
            System.out.println("No Result is found for the requested word");

    }

}