0% found this document useful (0 votes)
8 views1 page

Code

The document describes a function that sorts a list of numbers in ascending order using the bubble sort algorithm. It takes a list as input and returns a new sorted list without modifying the original. An example usage of the function is provided, demonstrating the sorting of a sample list.

Uploaded by

0ahmadsalim0
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views1 page

Code

The document describes a function that sorts a list of numbers in ascending order using the bubble sort algorithm. It takes a list as input and returns a new sorted list without modifying the original. An example usage of the function is provided, demonstrating the sorting of a sample list.

Uploaded by

0ahmadsalim0
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 1

"""

This function sorts a list of numbers in ascending order using the bubble sort
algorithm.

Args:
list_to_sort: A list of numbers to be sorted.

Returns:
A new list with the numbers sorted in ascending order.
"""
# Create a copy of the list to avoid modifying the original
sorted_list = list_to_sort.copy()
n = len(sorted_list)

# Iterate through the list n-1 times


for i in range(n-1):
# Flag to track if any swaps were made in a pass
swapped = False
# Iterate through the unsorted portion of the list
for j in range(n-i-1):
# Compare adjacent elements and swap if necessary
if sorted_list[j] > sorted_list[j+1]:
sorted_list[j], sorted_list[j+1] = sorted_list[j+1], sorted_list[j]
swapped = True
# If no swaps were made, the list is already sorted
if not swapped:
break

# Return the sorted list


return sorted_list

# Example usage
my_list = [1, 9, 5, 2, 1, 8, 6, 6, 3, 4, 10, 7]
sorted_list = sort_list(my_list)
print(sorted_list) # Output: [1, 1, 2, 3, 4, 5, 6, 6, 7, 8, 9, 10]

You might also like