From a81c546fc960433bafb688221100106bbf031e3c Mon Sep 17 00:00:00 2001 From: Shammy Raj Date: Tue, 24 Oct 2023 22:59:04 +0530 Subject: [PATCH] added insertion sort in python --- insertion sort.py | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 insertion sort.py diff --git a/insertion sort.py b/insertion sort.py new file mode 100644 index 0000000..45ca745 --- /dev/null +++ b/insertion sort.py @@ -0,0 +1,26 @@ +def insertion_sort(arr): + for i in range(1, len(arr)): + key = arr[i] + j = i - 1 + while j >= 0 and key < arr[j]: + arr[j + 1] = arr[j] + j -= 1 + arr[j + 1] = key + +def main(): + # Input a list of numbers + try: + input_str = input("Enter a list of numbers separated by spaces: ") + unsorted_list = [int(num) for num in input_str.split()] + except ValueError: + print("Invalid input. Please enter a list of numbers.") + return + + # Call the insertion_sort function to sort the list + insertion_sort(unsorted_list) + + # Display the sorted list + print("Sorted List:", unsorted_list) + +if __name__ == "__main__": + main()