In Python Generate a file that has 5000 random numbers in it

In Python:

Generate a file that has 5000 random numbers in it. (provide the code)

Using that file Do the following:

Create 3 programs that:

Implement the Bubble Sort

Implement the Insertion Sort

Implement the Selection Sort

Solution

def create_random():

   import random
   f = open(\'numbers.txt\',\'w\')
   N = 5000

   for i in xrange(N):  
       write = str(random.randint(0, 100000)) + \'\ \'
       f.write(write)

   f.close() # you can omit in most cases as the destructor will call it

def bubble_sort(arr):

for i in range(len(arr)):
# Last i elements are already in place
for j in range(0, len(arr)-i-1):
# traverse the array from 0 to n-i-1
# Swap if the element found is greater
# than the next element
if arr[j] > arr[j+1] :
arr[j], arr[j+1] = arr[j+1], arr[j]

return arr


# Function to do insertion sort
def insertion_sort(arr):

for i in range(1, len(arr)):

key = arr[i]
# Move elements of arr[0..i-1], that are
# greater than key, to one position ahead
# of their current position
j = i-1
while j >=0 and key < arr[j] :
arr[j+1] = arr[j]
j -= 1
arr[j+1] = key
return arr


def selection_sort(arr):
  
   for i in range(len(arr)):   
   # Find the minimum element in remaining , unsorted array
   min_idx = i
   for j in range(i+1, len(arr)):
   if arr[min_idx] > arr[j]:
   min_idx = j     
   # Swap the found minimum element with
   # the first element
   arr[i], arr[min_idx] = arr[min_idx], arr[i]
   return arr


create_random()
with open(\"numbers.txt\", \"r\") as ins:
array = []
for line in ins:
array.append(int(line))

print bubble_sort(array[:10])
print insertion_sort(array[:10])
print selection_sort(array[:10])

In Python: Generate a file that has 5000 random numbers in it. (provide the code) Using that file Do the following: Create 3 programs that: Implement the Bubble
In Python: Generate a file that has 5000 random numbers in it. (provide the code) Using that file Do the following: Create 3 programs that: Implement the Bubble

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site