Created
December 18, 2015 14:23
-
-
Save 5hirish/3af553bf8e33cc6cae41 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /usr/bin/python | |
import random | |
list = list() | |
t = 0 | |
for i in xrange(10): | |
list.append(random.randrange(1,100,1)) #generate a list of ten random numbers between 1 and 100 | |
print "The unsorted list : ",list | |
for j in xrange(len(list)-1): | |
smallest = 999 #initialise to a highest number - infinity | |
for i in range(j,len(list)): #loop with lower range skipping assinged elements | |
key = list[i] | |
if key < smallest: #compare the current with the smallest element | |
smallest = key #if small save it over the pervious | |
t = i #save the position too | |
list[t] = list[j] #swap the smallest with current element | |
list[j] = smallest | |
print "The smallest element for ",j," : ",smallest | |
print "The sorted list Ascending : ",list | |
t = 0 | |
for i in xrange(10): | |
list[i] = random.randrange(1,100,1) #generate a list of ten random numbers between 1 and 100 | |
print "The unsorted list : ",list | |
for j in xrange(len(list)-1): | |
greatest = -1 #initialise to a smallest number - infinity | |
for i in range(j,len(list)): #loop with lower range skipping assinged elements | |
key = list[i] | |
if key > greatest: #compare the current with the smallest element | |
greatest = key #if small save it over the pervious | |
t = i #save the position too | |
list[t] = list[j] #swap the smallest with current element | |
list[j] = greatest | |
print "The smallest element for ",j," : ",greatest | |
print "The sorted list Descending : ",list |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Answer to the Exercise question 2.2-2 by Introduction to Algorithms by CLRS.
The algorithm only requires to run on n-1 elements instead of n because the n'th element gets automatically sorted in the process of finding and swapping the smallest or largest number.