diff --git a/snippets/python/list-manipulation/sort-a-list-using-insertion-sort-algorithm.md b/snippets/python/list-manipulation/sort-a-list-using-insertion-sort-algorithm.md new file mode 100644 index 00000000..0cd6aa80 --- /dev/null +++ b/snippets/python/list-manipulation/sort-a-list-using-insertion-sort-algorithm.md @@ -0,0 +1,28 @@ +--- +title: sort a list using insertion sort algorithm +description: Insertion Sort +author: Simpfey +tags: list,sort +--- + +```py +def insertionSort(arr): + n = len(arr) # Get the length of the array + + if n <= 1: + return # If the array has 0 or 1 element, it is already sorted, so return + + for i in range(1, n): # Iterate over the array starting from the second element + key = arr[i] # Store the current element as the key to be inserted in the right position + j = i-1 + while j >= 0 and key < arr[j]: # Move elements greater than key one position ahead + arr[j+1] = arr[j] # Shift elements to the right + j -= 1 + arr[j+1] = key # Insert the key in the correct position + + return arr + +# Usage: +list = [6, 2, 3, 1, 4, 5] +insertionsort(list) # Returns: [1, 2, 3, 4, 5, 6] +``` diff --git a/snippets/python/list-manipulation/sort-a-list-using-quick-sort-algorithm.md b/snippets/python/list-manipulation/sort-a-list-using-quick-sort-algorithm.md new file mode 100644 index 00000000..672bdb78 --- /dev/null +++ b/snippets/python/list-manipulation/sort-a-list-using-quick-sort-algorithm.md @@ -0,0 +1,60 @@ +--- +title: sort A list using quick sort algorithm +description: sorts a list using Quick Sort Algorithm (Currently The Fastest) +author: Simpfey +tags: list,sort +--- + +```py +# Function to find the partition position +def partition(array, low, high): + + # choose the rightmost element as pivot + pivot = array[high] + + # pointer for greater element + i = low - 1 + + # traverse through all elements + # compare each element with pivot + for j in range(low, high): + if array[j] <= pivot: + + # If element smaller than pivot is found + # swap it with the greater element pointed by i + i = i + 1 + + # Swapping element at i with element at j + (array[i], array[j]) = (array[j], array[i]) + + # Swap the pivot element with the greater element specified by i + (array[i + 1], array[high]) = (array[high], array[i + 1]) + + # Return the position from where partition is done + return i + 1 + +# function to perform quicksort + + +def quickSort(array, low, high): + if low < high: + + # Find pivot element such that + # element smaller than pivot are on the left + # element greater than pivot are on the right + pi = partition(array, low, high) + + # Recursive call on the left of pivot + quickSort(array, low, pi - 1) + + # Recursive call on the right of pivot + quickSort(array, pi + 1, high) + + return array + +# Usage: +list = [6, 2, 3, 1, 4, 5] +list_len = len(list) + +quickSort(list, 0, list_len - 1) # Returns: [1, 2, 3, 4, 5, 6] +```