220,185 views
33 votes
33 votes
Design a program takes as input, X, an unsorted list of numbers, and returns the sorted list of numbers in X. The program must be based on the following strategy: Handle the case when X is empty and has only 1 item. Split X into two lists, using the split function in the previous problem. Sort L and G. Put everything together into a sorted list. Test your program with 10 different unsorted lists.

User Giusy
by
3.3k points

1 Answer

12 votes
12 votes

Answer:

The program in python is as follows:

def split(X):

L = []; G = []

for i in range(len(X)):

if X[i]>=X[0]:

G.append(X[i])

else:

L.append(X[i])

L.sort(); G.sort()

return L,G

X = []

n = int(input("Length of X: "))

for i in range(n):

inp = int(input(": "))

X.append(inp)

if len(X) == 0 or len(X) == 1:

print(X)

else:

X1,X2=split(X)

newList = sorted(X1 + X2)

print(newList)

Step-by-step explanation:

The following represents the split function in the previous problem

def split(X):

This initializes L and G to empty lists

L = []; G = []

This iterates through X

for i in range(len(X)):

All elements of X greater than 0 equal to the first element are appended to G

if X[i]>=X[0]:

G.append(X[i])

Others are appended to L

else:

L.append(X[i])

This sorts L and G

L.sort(); G.sort()

This returns sorted lists L and G

return L,G

The main function begins here

This initializes X

X = []

This gets the length of list X

n = int(input("Length of X: "))

This gets input for list X

for i in range(n):

inp = int(input(": "))

X.append(inp)

This prints X is X is empty of has 1 element

if len(X) == 0 or len(X) == 1:

print(X)

If otherwise

else:

This calls the split function to split X into 2

X1,X2=split(X)

This merges the two lists returned (sorted)

newList = sorted(X1 + X2)

This prints the new list

print(newList)

User Aitor
by
2.8k points