Animasi Insertion Sort || INFORMATIKA
Table of Contents
Introduction
This tutorial will guide you through the Insertion Sort algorithm, a fundamental sorting technique in computer science. Understanding Insertion Sort is essential for grasping more complex algorithms and data structures. This step-by-step guide will break down the process into manageable parts, ensuring you can implement it effectively.
Step 1: Understanding Insertion Sort
Insertion Sort is a simple sorting algorithm that builds a sorted array one element at a time. It works similarly to the way you might sort playing cards in your hands.
Key Characteristics
- Time Complexity: O(n^2) in the average and worst cases.
- Space Complexity: O(1) as it sorts in place.
- Stable: Maintains the relative order of equal elements.
Step 2: Visualize the Sorting Process
To grasp how Insertion Sort operates, visualize the following steps:
- Start with an unsorted array: For example, [5, 2, 9, 1, 5, 6].
- Begin with the second element: Compare it to the first one.
- Insert it in the correct position: Shift elements as necessary to make space for it.
Example Walkthrough
- Initial Array: [5, 2, 9, 1, 5, 6]
- After comparing and inserting 2: [2, 5, 9, 1, 5, 6]
- Continue this process for each subsequent element.
Step 3: Implementing the Algorithm
Here’s how to implement the Insertion Sort algorithm in Python:
def insertion_sort(arr)
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
return arr
Explanation of the Code
- The outer loop iterates through each element starting from the second.
- The inner loop compares the current element (
key
) to its predecessors and shifts them until the correct position is found. - Finally, the
key
is placed in its sorted position.
Step 4: Testing the Algorithm
To test your implementation:
- Create a list of numbers: For example,
numbers = [5, 2, 9, 1, 5, 6]
. - Call the function:
sorted_numbers = insertion_sort(numbers)
. - Print the result:
print(sorted_numbers)
should output[1, 2, 5, 5, 6, 9]
.
Step 5: Analyzing Performance
When using Insertion Sort, keep in mind the following:
- Best Case: When the array is already sorted, the time complexity is O(n).
- Worst Case: When the array is sorted in reverse order, the time complexity is O(n^2).
- Use Cases: Insertion Sort is efficient for small data sets or lists that are already partially sorted.
Conclusion
Insertion Sort is a straightforward yet powerful algorithm that is great for understanding sorting mechanisms. By visualizing the process, implementing the code, and testing it, you can fully grasp how it works. Next steps include experimenting with larger data sets or trying to optimize the algorithm for specific use cases. Happy coding!