Latest web development tutorials

Python includes exercises 37

Python 100 Li Python 100 Li

Title: 10 Number of sorts.

Program Analysis: You can use selection method, that is, from 9 comparison process, select a minimal exchange with the first element, the next and so on, that is, with the second element and after eight compared and exchanged.

Source Code:

#!/usr/bin/python
# -*- coding: UTF-8 -*-

if __name__ == "__main__":
    N = 10
    # input data
    print 'please input ten num:\n'
    l = []
    for i in range(N):
        l.append(int(raw_input('input a number:\n')))
    print
    for i in range(N):
        print l[i]
    print

    # sort ten num
    for i in range(N - 1):
        min = i
        for j in range(i + 1,N):
            if l[min] > l[j]:min = j
        l[i],l[min] = l[min],l[i]
    print 'after sorted'
    for i in range(N):
        print l[i]

The above example output is:

please input ten num:

input a number:
5
input a number:
3
input a number:
23
input a number:
67
input a number:
2
input a number:
56
input a number:
45
input a number:
98
input a number:
239
input a number:
9

5
3
23
67
2
56
45
98
239
9

after sorted
2
3
5
9
23
45
56
67
98
239

Python 100 Li Python 100 Li