Skip to content

Instantly share code, notes, and snippets.

@5hirish
Created December 18, 2015 14:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 5hirish/3af553bf8e33cc6cae41 to your computer and use it in GitHub Desktop.
Save 5hirish/3af553bf8e33cc6cae41 to your computer and use it in GitHub Desktop.
#! /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
@5hirish
Copy link
Author

5hirish commented Dec 18, 2015

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment