1. Home
  2. Explore
  3. Computer Science
  4. Programming Algorithms Explained

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

Programming Algorithms Explained

💻 Algorithms and Computational Complexity

Algorithms are specific steps used to complete a computation. While multiple algorithms can achieve the same result, some are more efficient than others. Efficiency is often measured by the number of steps an algorithm takes or the amount of memory it uses. The term "algorithm" originates from the Persian polymath Muḥammad ibn Mūsā al-Khwārizmī, a father of algebra. The study of efficient algorithms forms the core of Computer Science.


🔢 Sorting Algorithms: Organizing Data

Sorting is a fundamental algorithmic problem in computer science, used extensively in everyday applications like finding cheapest airfare, arranging emails, or scrolling contacts. Data is often represented in an array, which is a series of items.

📝 Selection Sort: A Basic Approach

Selection Sort is a straightforward algorithm for arranging items in ascending or descending order.

How it works (Ascending Order):

  1. Scan the entire array to find the smallest number.

  2. Swap this smallest number with the element at the first position of the array.

  3. Repeat the process for the remaining unsorted portion of the array, starting from the next position.

  4. Continue until the entire array is sorted.

Example with Airfare Prices:

  • Array: [307, 239, 214, 250, 384, 299, 223, 312]

  • Step 1: Smallest is 214. Swap 214 with 307. Array: [214, 239, 307, 250, 384, 299, 223, 312]

  • Step 2: (Ignoring 214) Smallest in [239, 307, 250, 384, 299, 223, 312] is 223. Swap 223 with 239. Array: [214, 223, 307, 250, 384, 299, 239, 312]

  • This continues until all elements are in order.

⏳ Computational Complexity: Big O Notation

The complexity of an algorithm describes the relationship between the input size (N) and the number of steps or time it takes to run. This is often expressed using Big O notation.

Selection Sort Complexity:

  • Selection Sort involves nested loops. One loop iterates through each position, and inside that, another loop finds the smallest remaining number.

  • If there are N items, it roughly performs N operations inside another N operations.

  • This results in a complexity of N squared (N²), written as O(N²).

Impact of N² Complexity:

  • For N = 8 items, steps ≈ 8² = 64.

  • For N = 80 items, steps ≈ 80² = 6,400.

  • Increasing input size by 10x (from 8 to 80) increases running time by 100x (from 64 to 6,400).

  • O(N²) is considered inefficient for large datasets.

🌳 Merge Sort: A More Efficient Alternative

Merge Sort is a more advanced and efficient sorting algorithm that uses a divide-and-conquer strategy.

How it works:

  1. Divide: Recursively splits the array into two halves until each subarray contains only one element. (An array of one element is inherently sorted).

  2. Conquer (Merge): Merges these single-element arrays back together, always ensuring that the merged array is sorted.

    It compares the first elements of two sorted subarrays, takes the smaller one, and repeats until all elements are merged into a larger sorted array.

Example with Airfare Prices:

  • Array: [307, 239, 214, 250, 384, 299, 223, 312] (N=8)

  • Split 1: [307, 239, 214, 250] and [384, 299, 223, 312] (N=4 each)

  • Split 2: [307, 239], [214, 250], [384, 299], [223, 312] (N=2 each)

  • Split 3: [307], [239], [214], [250], [384], [299], [223], [312] (N=1 each)

  • Merge 1:

    [307] and [239] merge to [239, 307]

  • [214] and [250] merge to [214, 250]

  • [384] and [299] merge to [299, 384]

  • [223] and [312] merge to [223, 312]

Merge 2:

  • [239, 307] and [214, 250] merge to [214, 239, 250, 307]

  • [299, 384] and [223, 312] merge to [223, 299, 312, 384]

Merge 3:

  • [214, 239, 250, 307] and [223, 299, 312, 384] merge to [214, 223, 239, 250, 299, 307, 312, 384]

Merge Sort Complexity:

  • The merging process involves comparing and moving items, which is proportional to N (the number of items).

  • The splitting process (how many times the array is halved) has a logarithmic relationship with N, specifically log₂N.

    For N=8, log₂8 = 3 splits.

  • For N=16, log₂16 = 4 splits.

Combined, Merge Sort has a complexity of N times log N (N log N), written as O(N log N).

Comparison of N² vs N log N:

  • O(N log N) is significantly more efficient than O(N²), especially for large datasets.

  • For N = 8000, log₂8000 is approximately 13.

  • N log N ≈ 8000 * 13 = 104,000 steps.

  • N² ≈ 8000² = 64,000,000 steps.

  • Merge Sort processes thousands of items with far fewer operations compared to Selection Sort.


🗺️ Graph Search Algorithms: Finding Optimal Paths

Graph search is another critical algorithmic problem, involving finding paths within a graph, which is a network of nodes (vertices) connected by lines (edges). Lines can have costs or weights associated with them, representing distance, time, or other metrics.

🗡️ Dijkstra's Algorithm: Shortest Path

Dijkstra's algorithm, conceived by Edsger Dijkstra in 1956, finds the shortest path between nodes in a graph with non-negative edge weights.

How it works (Finding the fastest route from Highgarden to Winterfell):

  1. Initialization:

    Assign a cost of 0 to the starting node (Highgarden).

  2. Assign an infinite cost (or unknown) to all other nodes.

  3. Keep track of the current lowest cost found for each node.

  4. Iteration:

    Select the unvisited node with the lowest current cost.

  5. For each neighbor of the selected node:

    Calculate the total cost to reach that neighbor through the current node (current node's cost + edge weight).

  6. If this new total cost is lower than the neighbor's current recorded cost, update the neighbor's cost and mark the current node as its predecessor in the path.

  7. Mark the selected node as visited.

  8. Repeat: Continue until the destination node is visited or all reachable nodes have been processed.

Example Steps:

  • Start at Highgarden (cost 0). All others ?.

  • Round 1 (from Highgarden):

    To King's Landing (cost 8).

  • To Riverrun (cost 10).

  • To Pyke (cost 14).

  • Highgarden is visited. Next lowest is King's Landing (8).

Round 2 (from King's Landing):

  • King's Landing (8) to The Trident (cost 5): Total 8 + 5 = 13.

  • King's Landing (8) to Riverrun (cost 25): Total 8 + 25 = 33. But Riverrun already has 10, so 33 is ignored.

  • King's Landing is visited. Next lowest is Riverrun (10).

Round 3 (from Riverrun):

  • Riverrun (10) to The Trident (cost 2): Total 10 + 2 = 12. Update The Trident from 13 to 12.

  • Riverrun (10) to Pyke (cost 3): Total 10 + 3 = 13. Update Pyke from 14 to 13.

  • Riverrun is visited. Next lowest is The Trident (12).

Round 4 (from The Trident):

  • The Trident (12) to Winterfell (cost 10): Total 12 + 10 = 22.

  • The Trident is visited. Next lowest is Pyke (13).

Round 5 (from Pyke):

  • Pyke (13) to Winterfell (cost 18): Total 13 + 18 = 31. 22 is lower than 31, so 22 remains the shortest path.

Result: The shortest path to Winterfell has a total cost of 22 weeks.

📈 Dijkstra's Algorithm Complexity

  • Original Dijkstra's Algorithm: Had a complexity of N², where N is the number of nodes in the graph. O(N²).

  • Improved Dijkstra's Algorithm: Later improvements reduced its complexity to O(N log N + M), where:

    N is the number of nodes.

  • M is the number of lines (edges).

This improved version is significantly faster and scalable for large graphs, such as entire road maps. For a graph with 6 cities (N=6) and 9 lines (M=9), the original N² would be 36 operations, while the improved version would be approximately 14 operations.


🌐 Algorithms in the Modern World

Algorithms are ubiquitous and essential for the modern world. Every time you use services like Google Maps for directions, a graph search algorithm similar to Dijkstra's is at work. Computer scientists constantly leverage existing algorithms and develop new ones to solve complex problems and improve efficiency.

Ask anything

We've read this whole study set, so questions about it get the best answers.

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent