使用Python插入排序

使用Python进行数据结构操作比较少见,但为了更深入的理解Python的操作原理,提升自己的算法能力。我决定认真过一遍 普林斯顿大学教授Robert Sedgewick主讲的《Algorithms》 更多见:iii.run

【普林斯顿算法下载链接】普林斯顿大学教授Robert Sedgewick主讲的《Algorithms》

使用C++插入排序

#include<iostream>
using namespace std;
int main() {
    int a[] = { 4,3,9,0,1,2,5,6,7,8 };
    for(int i = 1; i < 10; i++) {
        int key = a[i];
        int j = i - 1;
        while (j >= 0&&a[j] > key) {
            a[j + 1] = a[j];  
            j--;
        }
        a[j + 1] = key;
    }
    for (int i = 0; i < 10; i++) {
        cout << a[i];
    }
    cout << endl;
    return 0;
}

这一段比较简单,我也就不多说了。

使用Python进行排序

data = [4,3,9,0,1]
for i in range(1,len(data)):
    key = data[i]
    j = i - 1
    while j >= 0 and data[j] > key:
            data[j+1]=data[j]
            j = j - 1
    data[j+1] = key
print(data)

总结:

  • Python的确比CPP简洁得多;
  • while循环体中条件部分可以使用 and ,不能用&&
  • python没有{},需要对齐,输入Tab或者敲空格。
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容