Skip to content

[Edit] General: heap sort #7128

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 27 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
d0dd9bd
[Edit] SQL: DATEDIFF()
mamtawardhani May 21, 2025
9f5c19b
Update datediff.md
mamtawardhani May 21, 2025
c32e9f3
Merge branch 'Codecademy:main' into main
mamtawardhani May 23, 2025
4170ba2
Merge branch 'Codecademy:main' into main
mamtawardhani May 23, 2025
8325585
Merge branch 'Codecademy:main' into main
mamtawardhani May 26, 2025
8f6f8e8
Merge branch 'Codecademy:main' into main
mamtawardhani May 27, 2025
e4c54e8
Merge branch 'Codecademy:main' into main
mamtawardhani May 28, 2025
7b3b9c0
Merge branch 'Codecademy:main' into main
mamtawardhani May 29, 2025
27ecefd
Merge branch 'Codecademy:main' into main
mamtawardhani May 29, 2025
0392da4
Merge branch 'Codecademy:main' into main
mamtawardhani May 30, 2025
d550fa7
Merge branch 'Codecademy:main' into main
mamtawardhani Jun 2, 2025
793be7d
Merge branch 'Codecademy:main' into main
mamtawardhani Jun 3, 2025
2f03b61
Merge branch 'Codecademy:main' into main
mamtawardhani Jun 3, 2025
25eb0ab
Merge branch 'Codecademy:main' into main
mamtawardhani Jun 3, 2025
73e0e3b
Merge branch 'Codecademy:main' into main
mamtawardhani Jun 4, 2025
44f4c63
Merge branch 'Codecademy:main' into main
mamtawardhani Jun 5, 2025
545a8da
Merge branch 'Codecademy:main' into main
mamtawardhani Jun 6, 2025
49d85cd
Merge branch 'Codecademy:main' into main
mamtawardhani Jun 9, 2025
f488437
Merge branch 'Codecademy:main' into main
mamtawardhani Jun 10, 2025
9b642e6
Merge branch 'Codecademy:main' into main
mamtawardhani Jun 11, 2025
afb1cf5
Merge branch 'Codecademy:main' into main
mamtawardhani Jun 12, 2025
dc740fb
Merge branch 'Codecademy:main' into main
mamtawardhani Jun 13, 2025
6a579a7
Merge branch 'Codecademy:main' into main
mamtawardhani Jun 16, 2025
7975f75
Merge branch 'Codecademy:main' into main
mamtawardhani Jun 17, 2025
963fd46
Merge branch 'Codecademy:main' into main
mamtawardhani Jun 18, 2025
dd1ef4a
[Edit] SwiftUI: UIKit
mamtawardhani Jun 18, 2025
22569e9
[Edit] General: heap sort
mamtawardhani Jun 18, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 47 additions & 12 deletions content/general/concepts/algorithm/terms/heap-sort/heap-sort.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,16 +6,21 @@ Subjects:
Tags:
- 'Algorithms'
- 'Arithmetic'
- 'Sorting Algorithms'
- 'Heap Sort'
- 'Sorting Algorithms'
CatalogContent:
- 'learn-java'
- 'paths/computer-science'
---

**Heap Sort** is an efficient comparison-based sorting algorithm that outperforms simple algorithms like Bubble Sort, Insertion Sort, or Selection Sort. It builds upon the idea of Selection Sort but improves it by leveraging a binary heap to quickly find the maximum (or minimum) value. This significantly speeds up the process of sorting an array by moving the maximum element to the end in each iteration.
**Heap Sort** is a comparison-based sorting algorithm that organizes data using a binary heap—a special tree structure where the parent is always greater (in a max heap) than its children. It repeatedly extracts the largest element (the root), swaps it with the last unsorted item, and then re-heapifies the remaining elements. This continues until the array is fully sorted. It runs in O(n log n) time and is an in-place sort, meaning it uses no extra space.

Use cases for Heap Sort include:

The efficiency of Heap Sort comes from using a binary heap structure, a complete binary tree where every level is filled except possibly the last. In this structure, each parent node is greater than or equal to its children (max-heap). This property ensures that the root node always contains the largest element, which can then be moved to the end of the array.
- When consistent performance across best, average, and worst cases is important
- In embedded systems or low-memory environments due to its minimal space needs
- For implementing priority queues and scheduling algorithms
- In real-time systems where the maximum or minimum must be accessed quickly

A heap can be easily represented in an array. The root node is the first element, and the rest of the tree is stored level by level, from left to right. For any node at index `i`, its left child is at `2*i + 1` and its right child is at `2*i + 2`.

Expand All @@ -25,23 +30,35 @@ A heap can be easily represented in an array. The root node is the first element

A brief explanation of the Heap Sort algorithm steps:

- Initially, the input array needs to be heapified. That means we need to build a heap from the unsorted array. What is the heap and how can it be represented by an array is explained above. Remind that the heapified array is not sorted yet!
1\. Build a Max Heap

- The Heapify process rests upon building a structure of parents and descendants where a parent can be calculated as **(i - 1) / 2** where _i_ is an index of a descendant and simultaneously the left descendant can be calculated as **(2\*j + 1)** and the right descendant as **(2\*j + 2)** where _j_ is the index of the parent.
- Start by converting the given unsorted array into a Max Heap.
- A Max Heap is a complete binary tree where each parent node is greater than or equal to its children.
- This step ensures the largest value is always at the root (index 0 of the array).
- To do this, iterate over the array and apply the heapify-up (or up()) method for each element.

- Building of the heap itself is usually written in an **up** method which checks each node if it doesn't violate the rule mentioned in the point above (if it isn't greater than its parent). To prevent transferring the problem just a level up the check has to be called in a cycle for each node. When the checking cycle reaches the end of the array we can be sure it's heapified.
2\. Swap the Root with the Last Element

- Heap sort is an in-place comparison sorting algorithm: This means that it doesn't require additional memory beyond the input array and elements are compared to determine their relative order.
- The maximum element (at the root) is swapped with the last element in the heap.
- This effectively moves the largest element to its final sorted position at the end of the array.

- The sorting of the heap is basically made by the Selection sort. The array is divided into two parts (two subarrays): the unsorted subarray at the beginning and the sorted subarray at the end. Initially, the sorted subarray is empty, and the unsorted subarray contains all the elements. The sorted subarray gradually grows and the unsorted subarray shrinks until no elements remain in the unsorted part. The main advantage compared to Selection sort is finding the maximum which takes a constant time because it lies on the index "0". Swapping of the last node to the root (mentioned below) is also constant.
3\. Shrink the Heap

- Heap sort run on a heap tears away the maximum (the root node) and puts it to the end of the sorted subarray. Then it moves the last node to the root (as mentioned above). After such swapping the heap becomes "broken" and needs to be heapified again. For this purpose is usually used a **down** method which repairs the heap. The method is analogous to the **up** method. It is called on the root node and when it finds a descendant greater than the root it swaps it (if both descendants are greater it chooses the greater one). Again to prevent transferring the problem just a level down the check has to be called. This time we check if descendant nodes aren't greater than parents (how to find them is explained above). If they don't pass the check the swap must be made. We repeat that in each level if necessary but not for each node as in the **up** method so that is the point where the complexity is reduced.
- After swapping, ignore the last element (since it's sorted) by reducing the size of the heap by one.
- The rest of the array still needs to be sorted.

- Given that the algorithm has a time complexity of _O(n\*log n)_ in all cases, where _n_ is the number of elements in the array. It performs _n_ iterations of the **up** method (to build a heap) and the _log n_ factor comes from the height of the binary heap (a count of its levels).
4\. Restore the Max Heap

- This makes the algorithm efficient for large input sizes. Compared to other smart sorting algorithms Heap Sort might be better understandable because there is no need for using more advanced concepts such as recursions. Memory requirements can also be minimal (compared to Merge Sort which needs additional memory).
- After swapping, the heap property may be broken, so we need to rebuild the heap for the reduced array.
- Apply the heapify-down (or down()) method starting from the root to restore the Max Heap property.

- On the other hand, it is unstable (it may rearrange the relative order) and slower than the other smart sorting algorithms. Typically 2-3 times slower than well-implemented QuickSort.
5\. Repeat the Process

- Continue steps 2–4:
- Swap the new root with the last unsorted element,
- Shrink the heap,
- Heapify the root again.
- Repeat this until only one element remains unsorted—at that point, the entire array is sorted.

**Animation of Heap Sort:**

Expand Down Expand Up @@ -124,3 +141,21 @@ The output for the above code is:
Sorted array:
1 2 3 7 17 19 25 36 100
```

## Frequently Asked Questions

### 1. What is the time complexity of Heap Sort?

Heap Sort has a time complexity of O(n log n) in all cases—best, average, and worst. This is because:

- Building the heap takes O(n) time.
- Each of the n elements is extracted in log n time (due to heapify), giving O(n log n) total.

### 2. Is Heap Sort a stable sorting algorithm?

No, Heap Sort is not stable. Stability means elements with equal keys retain their original relative positions, which Heap Sort does not guarantee since it relies on swapping elements in a heap structure.

### 3. What is the difference between heap sort and merge sort?

- Heap Sort is an in-place, comparison-based algorithm that uses a binary heap to sort elements and is not stable.
- Merge Sort is a divide-and-conquer algorithm that uses additional memory, is stable, and often faster in practice.
198 changes: 190 additions & 8 deletions content/swiftui/concepts/uikit/uikit.md
Original file line number Diff line number Diff line change
@@ -1,22 +1,204 @@
---
Title: 'UIKit'
Description: 'UIKit is a foundational framework for building user interfaces in iOS, iPadOS, and tvOS applications.'
Description: 'Constructs and manages graphical, event-driven user interfaces for iOS, iPadOS, and tvOS applications.'
Subjects:
- 'Computer Science'
- 'Mobile Development'
- 'iOS'
Tags:
- 'SwiftUI'
- 'iOS'
- 'Mobile Development'
- 'UI'
- 'User Interface'
CatalogContent:
- 'learn-swift'
- 'paths/build-ios-apps-with-swiftui'
---

**UIKit** is a foundational framework for building user interfaces in iOS, iPadOS, and tvOS applications. It provides a comprehensive set of components and tools that enable developers to create visually appealing and interactive user interfaces. UIKit was introduced in 2007 alongside the first iPhone and became publicly available in 2008 with the release of the iPhone Software Development Kit (SDK). It quickly became the standard framework for iOS app development.
**UIKit** is Apple's imperative framework for constructing and managing graphical, event-driven user interfaces for iOS, iPadOS, and tvOS applications. Launched in 2008 alongside the original iPhone SDK, UIKit provides the foundational components and architectural patterns that enable developers to create interactive user experiences across Apple's mobile and television platforms.

UIKit serves as the traditional approach for iOS development, offering a mature and comprehensive set of user interface components, view controllers, and event handling mechanisms. The framework defines the core visual elements of iOS applications, from basic labels and buttons to sophisticated table views and navigation controllers.

## Key Components of UIKit

UIKit encompasses several fundamental classes and architectural patterns that form the backbone of iOS user interface development.

### UIView

**UIView** is the fundamental building block for all user interface elements in UIKit. Every visual component that appears on screen inherits from UIView.

```swift
class CustomView: UIView {
override func draw(_ rect: CGRect) {
// Draw blue background
let context = UIGraphicsGetCurrentContext()
context?.setFillColor(UIColor.blue.cgColor)
context?.fill(rect)
}

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
// Handle touch events
print("View was touched")
}
}
```

### UIViewController

**UIViewController** manages a single screen of content and serves as the controller in the Model-View-Controller pattern.

```swift
class MainViewController: UIViewController {
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var actionButton: UIButton!

override func viewDidLoad() {
super.viewDidLoad()
// Configure UI elements when view loads
titleLabel.text = "Welcome to UIKit"
actionButton.setTitle("Get Started", for: .normal)
}

@IBAction func actionButtonTapped(_ sender: UIButton) {
// Handle button tap event
let nextVC = DetailViewController()
present(nextVC, animated: true)
}
}
```

### Interface Builder and Storyboards

**Interface Builder** is a visual design tool integrated into Xcode. **Storyboards** contain the visual representation of an app's user interface.

```swift
class ProfileViewController: UIViewController {
@IBOutlet weak var profileImageView: UIImageView!
@IBOutlet weak var nameLabel: UILabel!

override func viewDidLoad() {
super.viewDidLoad()
// Configure profile image to be circular
profileImageView.layer.cornerRadius = 50
profileImageView.clipsToBounds = true
}
}
```

### Delegates and Data Sources

**Delegate pattern** enables objects to communicate without tight coupling. Data sources provide the data that views need to display.

```swift
class ContactsViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
private var contacts: [Contact] = []

override func viewDidLoad() {
super.viewDidLoad()
// Set table view delegate and data source
tableView.delegate = self
tableView.dataSource = self
}
}

extension ContactsViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return contacts.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// Create cell for each contact
let cell = tableView.dequeueReusableCell(withIdentifier: "ContactCell", for: indexPath)
cell.textLabel?.text = contacts[indexPath.row].name
return cell
}
}
```

### Auto Layout

**Auto Layout** is UIKit's constraint-based layout system for creating adaptive user interfaces.

```swift
class ConstraintExampleViewController: UIViewController {
private let titleLabel = UILabel()
private let actionButton = UIButton(type: .system)

override func viewDidLoad() {
super.viewDidLoad()
setupViews()
}

private func setupViews() {
// Configure views
titleLabel.text = "Auto Layout Example"
actionButton.setTitle("Continue", for: .normal)

// Add to view hierarchy
view.addSubview(titleLabel)
view.addSubview(actionButton)

// Disable autoresizing masks
titleLabel.translatesAutoresizingMaskIntoConstraints = false
actionButton.translatesAutoresizingMaskIntoConstraints = false

// Set up constraints
NSLayoutConstraint.activate([
titleLabel.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 32),
titleLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor),
actionButton.topAnchor.constraint(equalTo: titleLabel.bottomAnchor, constant: 24),
actionButton.centerXAnchor.constraint(equalTo: view.centerXAnchor)
])
}
}
```

## Advantages

- **Mature and Stable Framework:** Refined since 2008 with extensive documentation and proven patterns
- **Comprehensive Component Library:** Pre-built navigation controllers, table views, and specialized controls
- **Precise Control:** Granular control over UI behavior, animations, and performance
- **Broad Platform Support:** Supports iOS 2.0+ for wide device compatibility
- **System Integration:** Native access to Core Data, animations, and device capabilities

## Limitations

- **Verbose Code** - Requires more boilerplate code than modern declarative frameworks
- **Complex State Management** - UI state synchronization becomes challenging in large applications
- **Steep Learning Curve** - Requires understanding multiple design patterns and concepts
- **Limited Reactive Support** - Needs adaptation layers for modern reactive programming
- **Memory Management** - Requires attention to retain cycles and view hierarchy complexity

## SwiftUI vs UIKit Comparison

| Feature | SwiftUI | UIKit |
| ------------------------------ | ---------------------------------------------- | --------------------------------- |
| **Development Approach** | Declarative | Imperative |
| **Code Verbosity** | Concise syntax | Verbose implementation |
| **Learning Curve** | Moderate for beginners | Steep, requires pattern knowledge |
| **State Management** | Built-in (@State, @Binding, @ObservableObject) | Manual implementation required |
| **Live Previews** | Native Xcode support | Limited preview capabilities |
| **Animation System** | Simplified animation APIs | Powerful but complex animations |
| **Customization Level** | Growing but limited | Extensive customization options |
| **Platform Support** | iOS 13+, macOS 10.15+ | iOS 2.0+, all versions |
| **Community Resources** | Growing ecosystem | Mature, extensive resources |
| **Third-party Integration** | Limited library support | Extensive library ecosystem |
| **Performance Optimization** | Automatic optimizations | Manual optimization required |
| **Debugging Tools** | SwiftUI-specific debugging | Mature debugging infrastructure |
| **Interface Design** | Code-only approach | Interface Builder + code options |
| **Data Flow** | Reactive, automatic updates | Manual data binding |
| **Cross-platform Development** | Apple platforms only | iOS/iPadOS/tvOS focused |

## Frequently Asked Questions

### 1. What is the difference between UIKit and SwiftUI?

UIKit is Apple's traditional imperative framework requiring explicit UI management, while SwiftUI is the newer declarative framework with automatic state-driven updates. UIKit offers more control and customization; SwiftUI provides simpler syntax.

Objective-C, the primary programming language for iOS development at that time, played a vital role in the adoption and implementation of UIKit. Developers used Objective-C to write code that utilized UIKit's classes, methods, and APIs to create user interfaces.
### 2. Is UIKit still relevant in modern iOS development?

## UIKit vs. SwiftUI
Yes, UIKit remains highly relevant and is the primary framework for many iOS applications. It continues receiving updates and is essential for complex applications requiring fine-grained control.

Despite the introduction of SwiftUI in 2019, UIKit remains an essential part of the iOS development ecosystem. While SwiftUI offers a modern and intuitive way to design interfaces, UIKit provides a robust and mature set of APIs that SwiftUI can leverage. This allows developers to combine the power of both frameworks, using UIKit for certain UI components or integrating existing UIKit-based code into SwiftUI projects.
### 3. Can I use UIKit and SwiftUI in the same project?

With the release of Swift in 2014 as an alternative programming language for iOS development, developers gained the option to write iOS apps using Swift instead of Objective-C.
Yes, Apple provides integration mechanisms. Use `UIHostingController` to embed SwiftUI in UIKit, and `UIViewRepresentable` to integrate UIKit components into SwiftUI.