Respuesta :
Answer:
Bubble Sort
- import random
- n = int(input("Input a number: "))
- numList = []
- for i in range(0, n):
- numList.append(random.randint(0, 1000))
- print(numList)
- for i in range(n):
- status = False
- for j in range(0, n - i - 1):
- if(numList[j] > numList[j+1]):
- temp = numList[j]
- numList[j] = numList[j+1]
- numList[j+1] = temp
- status = True
- if status == False:
- break
- print(numList)
Selection sort
- import random
- n = int(input("Input a number: "))
- numList = []
- for i in range(0, n):
- numList.append(random.randint(0, 1000))
- print(numList)
- for i in range(n):
- currentMin = numList[i]
- index = i
- for j in range(i+1, n):
- if(currentMin > numList[j]):
- currentMin = numList[j]
- index = j
- temp = numList[i]
- numList[i] = currentMin
- numList[index] = temp
- print(numList)
Explanation:
The solution code is written in Python 3.
Bubble Sort version
Firstly import the random module in order to generate random number in the later stage (Line 1). Next, prompt user to input a number and use randint method to generate random integer between 0 - 1000 and add it to the numList (Line 2 - 6). Print the original numList to terminal (Line 8).
Start the bubble sort algorithm (Line 10 - 21). The idea is to create a for-loop to traverse through each number from the numList and compare it with its neighbouring value. if the left value is bigger than the right value, swap the two numbers. This process will be ongoing until the end of the loop. Print the sorted list to the terminal (Line 23).
Selection Sort version
By using the same process, the program prompts user input a number and generate the random integer (Line 1- 8).
Start selection algorithm (Line 10 - 21). Create a for loop to traverse through each number from numList. Set the value addressed by current i index as current minimum (Line 11). Create an inner for loop to compare the current minimum with the subsequent elements from the numList. If there is any subsequent element smaller than the current minimum, swap their position in the numList. This process will be ongoing till finishing the outer loop. Print the sorted list to the terminal (Line 23).
