python 3中的bubblesort函数

时间:2017-01-11 00:41:53

标签: python bubble-sort

我试图理解冒泡套的工作原理。我知道这里有多个线索,但它们都是功能的不同版本,并没有很好地向新手解释。我在youtube上找到了一个简洁的代码:

if ( 3 + 6 ) {
    // print 3+6;
} 

// The 3 + 6 either if using hard coded numbers or variable 
// is an expression and it will evaluate to some value. 
// Does this make sense to you?
if ( 9 ) {
    // do something;
}

// A constant value or variable, a constant expression will 
// always evaluate to true if used as a condition. 
// How can 9 every return false?

// If statements are designed to handle true or false conditions or comparisons.

// Boolean
bool imHappy = true;
if ( imHappy ) {
   // print( smiley face );
} else {
   // print ( frown );
}

// Or it could be written this way as well
if ( !imHappy ) {
      // print( frown );
} else {
      // print( smiley face );
}

// Logical Comparison 
const int adultAge = 18;
const int legalAge = 21;
int consumersAge = 0;

std::cout << "Can I see your ID?" << std::endl;
std::cin >> consumerAge; // Read of from DOB on ID

if ( consumerAge > 0 && consumerAge < adultAge ) {
    std::cout << "Sorry we can not do any of the following: \n"
              << "Sell you any tobacco products\n"  
              << "Serve you alcohol\n"
              << "Sell you lottery or allow you to gamble." << std::endl;
else if ( consumerAge >= adultAge && consumerAge < legalAge ) {
    std::cout << "Sorry we can not do any of the following: \n"
              << "Serve you Alcohol or Allow You To Gamble. \n"
              << "You are able to purchase: Tobacco and Lottery Tickets." << std::endl;
} else if ( consumerAge >= legalAge ) {
    std::cout << "You may purchase everything we sell and you are allowed to gamble." << std::endl;
} else {
     std::cout << "Invalid age entered: Are you even born yet?\n"
               << "You can not be " << consumerAge << " years old!" << std::endl;
} 

有人可以向我解释第3行的目的吗在哪里说len(mylist) - 1 - i?我们为什么要减去i? mylist做什么?

我是一名初学程序员,只是想更好地了解这些循环是如何工作的。

1 个答案:

答案 0 :(得分:2)

这是因为每次迭代后,最后一个数字都会被排序。详细说明一下,让我们看看这个清单:

[0, 2, 5, 7, 3, 1]

第一次排序后,将对最大的数字进行排序。在第二次排序之后,第二大数字已经排序。或者基本上,索引len(myList ) - 1 - iteration处的数字已经被排序并且将处于正确的位置。在第一次排序之后,最大数量到位。最大数字的索引现在为len(myList) - 1。然后将正确放置第二大数字,此iteration从0变为1,因此第二大数字的索引现在是len(myList) - 1 - iterationlen(myList) - 1 - 1,它位于最大数字之前。