From d0dd9bd3c5a7c5188d3f803a5fd3b6f051a800d3 Mon Sep 17 00:00:00 2001 From: Mamta Wardhani Date: Wed, 21 May 2025 16:08:19 +0530 Subject: [PATCH 1/4] [Edit] SQL: DATEDIFF() --- .../concepts/dates/terms/datediff/datediff.md | 191 ++++++++++++++---- 1 file changed, 154 insertions(+), 37 deletions(-) diff --git a/content/sql/concepts/dates/terms/datediff/datediff.md b/content/sql/concepts/dates/terms/datediff/datediff.md index 66f952e9b2e..9426633b080 100644 --- a/content/sql/concepts/dates/terms/datediff/datediff.md +++ b/content/sql/concepts/dates/terms/datediff/datediff.md @@ -1,72 +1,189 @@ --- Title: 'DATEDIFF()' -Description: 'Calculates and returns the difference between two date values. Available in SQL Server and MySQL.' +Description: 'Calculates the difference between two date or timestamp values and returns the result as an integer.' Subjects: - - 'Data Science' + - 'Computer Science' + - 'Web Development' Tags: - 'Database' - 'Date' - - 'Queries' - - 'MySQL' - - 'SQL Server' + - 'Functions' + - 'SQL' CatalogContent: - 'learn-sql' - 'paths/analyze-data-with-sql' - - 'paths/design-databases-with-postgresql' --- -**`DATEDIFF()`** is a function found in SQL Server and MySQL that calculates and returns the difference between two date values. +The **`DATEDIFF()`** function calculates the difference between two date or timestamp values and returns the result as an integer in a specified unit of time. This powerful function allows developers and analysts to easily measure time intervals between dates, which is essential for reporting, data analysis, and application development. -## SQL Server Syntax +`DATEDIFF()` serves as a cornerstone for date-based calculations in SQL Server, enabling users to perform operations like calculating ages, measuring durations of events, determining time elapsed between transactions, and creating date-based business metrics. Its versatility makes it invaluable for virtually any application that deals with temporal data. + +## Syntax ```pseudo -DATEDIFF(datePart, date1, date2) +DATEDIFF(interval, date1, date2) ``` -The `DATEDIFF()` function in SQL Server has three required parameters: +**Parameters:** + +- `interval`: The time unit in which the difference will be calculated. Valid values include: + - `year`, `yy`, `yyyy`: Years + - `quarter`, `qq`, `q`: Quarters + - `month`, `mm`, `m`: Months + - `dayofyear`, `dy`, `y`: Day of the year + - `day`, `dd`, `d`: Days + - `week`, `wk`, `ww`: Weeks + - `hour`, `hh`: Hours + - `minute`, `mi`, `n`: Minutes + - `second`, `ss`, `s`: Seconds + - `millisecond`, `ms`: Milliseconds + - `microsecond`, `mcs`: Microseconds + - `nanosecond`, `ns`: Nanoseconds +- `date1`: The start date for the calculation. Can be a date, datetime, datetime2, smalldatetime, or time data type, or an expression that resolves to one of these types. +- `date2`: The end date for the calculation. Can be a date, datetime, datetime2, smalldatetime, or time data type, or an expression that resolves to one of these types. + +**Return value:** -- `datePart` is the part of the date to return. It can be one of the following formats: - - Year: `year`, `yyyy`, `yy` - - Quarter: `quarter`, `qq`, `q` - - Week: `week`, `ww`, `wk` - - Weekday: `weekday`, `dw`, `w` - - Second: `second`, `ss`, `s` - - Month: `month`, `mm`, `m` - - Minute: `minute`, `mi`, `n` - - Millisecond: `millisecond`, `ms` - - Hour: `hour`, `hh` - - Day of Year: `dayofyear` - - Day: `day`, `dy`, `y` -- `date1` and `date2` are the dates to compare. It can be in several formats, one being the `yyyy/mm/dd` format. +The `DATEDIFF()` function returns an integer representing the number of time units (specified by the interval parameter) between date1 and date2. -### Example 1 +## Example 1: Basic Date Difference Calculation -The following example calculates the difference in months between `2020/05/18` and `2022/05/18`: +This example demonstrates how to calculate the difference between two dates in various time intervals: ```sql -SELECT DATEDIFF(month, '2020/05/18', '2022/05/18'); /* Output: 24 */ +-- Calculate difference between two dates in years, months, and days +SELECT + DATEDIFF(year, '2020-01-15', '2023-09-20') AS YearDiff, + DATEDIFF(month, '2020-01-15', '2023-09-20') AS MonthDiff, + DATEDIFF(day, '2020-01-15', '2023-09-20') AS DayDiff; ``` -### Example 2 +Output produced by this code will be: + +| YearDiff | MonthDiff | DayDiff | +| -------- | --------- | ------- | +| 3 | 44 | 1344 | + +This example calculates the difference between January 15, 2020, and September 20, 2023, in years, months, and days. The results show there are 3 years, 44 months, or 1344 days between these dates. + +## Example 2: Calculating Age in Years -The following example returns the difference in seconds between `2021/09/30 08:22:04` and `2021/09/30 08:25:06`: +This example demonstrates how to use `DATEDIFF()` to calculate a person's age in years from their birthdate. ```sql -SELECT DATEDIFF(second, '2021/09/30 08:22:04', '2021/09/30 08:25:06'); /* Output: 182 */ +-- Create a sample table with employee data +CREATE TABLE Employees ( + EmployeeID INT PRIMARY KEY, + FirstName VARCHAR(50), + LastName VARCHAR(50), + BirthDate DATE, + HireDate DATE +); + +-- Insert sample data +INSERT INTO Employees (EmployeeID, FirstName, LastName, BirthDate, HireDate) +VALUES + (1, 'John', 'Smith', '1985-06-15', '2010-03-20'), + (2, 'Sarah', 'Johnson', '1992-11-30', '2015-07-10'), + (3, 'Michael', 'Brown', '1978-02-23', '2005-09-15'); + +-- Calculate ages as of current date +SELECT + EmployeeID, + FirstName + ' ' + LastName AS EmployeeName, + BirthDate, + DATEDIFF(year, BirthDate, GETDATE()) AS Age +FROM + Employees +ORDER BY + Age DESC; ``` -## MySQL Syntax +The output generated by this code will be: -MySQL only requires two date parameters in the `DATEDIFF()` function and will return the number of days between `date1` and `date2`. +| EmployeeID | EmployeeName | BirthDate | Age | +| ---------- | ------------- | ---------- | --- | +| 3 | Michael Brown | 1978-02-23 | 47 | +| 1 | John Smith | 1985-06-15 | 39 | +| 2 | Sarah Johnson | 1992-11-30 | 32 | -```pseudo -DATEDIFF(date1, date2) -``` +This example shows how to calculate an employee's age by finding the difference in years between their birthdate and the current date. Note that this calculation provides the raw year difference and doesn't account for whether the birthday has occurred yet in the current year. -### Example +## Example 3: Business Metrics with `DATEDIFF()` -The following example returns the difference in days between `2019-07-05` and `2018-12-24`: +This example demonstrates how to use `DATEDIFF()` for business reporting metrics, such as calculating order processing times and identifying delayed shipments. ```sql -SELECT DATEDIFF("2019-07-05", "2018-12-24"); /* Output: 193 */ +-- Create sample orders table +CREATE TABLE Orders ( + OrderID INT PRIMARY KEY, + CustomerID INT, + OrderDate DATETIME, + ShipDate DATETIME, + DeliveryDate DATETIME +); + +-- Insert sample data +INSERT INTO Orders (OrderID, CustomerID, OrderDate, ShipDate, DeliveryDate) +VALUES + (1001, 101, '2023-01-10 09:30:00', '2023-01-11 14:15:00', '2023-01-15 11:20:00'), + (1002, 102, '2023-01-12 13:45:00', '2023-01-13 10:30:00', '2023-01-14 16:45:00'), + (1003, 103, '2023-01-15 11:20:00', '2023-01-18 09:45:00', '2023-01-22 13:10:00'), + (1004, 104, '2023-01-16 14:55:00', '2023-01-17 16:30:00', '2023-01-21 09:30:00'), + (1005, 105, '2023-01-18 10:15:00', NULL, NULL); + +-- Calculate processing, shipping, and total handling times +SELECT + OrderID, + OrderDate, + ShipDate, + DeliveryDate, + -- Processing time (from order to shipment) + DATEDIFF(hour, OrderDate, ShipDate) AS ProcessingHours, + -- Shipping time (from shipment to delivery) + DATEDIFF(day, ShipDate, DeliveryDate) AS ShippingDays, + -- Total time (from order to delivery) + DATEDIFF(day, OrderDate, DeliveryDate) AS TotalDays, + -- Identify delayed shipments (processing > 24 hours) + CASE + WHEN DATEDIFF(hour, OrderDate, ShipDate) > 24 THEN 'Delayed' + ELSE 'On Time' + END AS ShipmentStatus +FROM + Orders +WHERE + ShipDate IS NOT NULL; ``` + +The output of this code will be: + +| OrderID | OrderDate | ShipDate | DeliveryDate | ProcessingHours | ShippingDays | TotalDays | ShipmentStatus | +| ------- | ------------------- | ------------------- | ------------------- | --------------- | ------------ | --------- | -------------- | +| 1001 | 2023-01-10 09:30:00 | 2023-01-11 14:15:00 | 2023-01-15 11:20:00 | 29 | 4 | 5 | Delayed | +| 1002 | 2023-01-12 13:45:00 | 2023-01-13 10:30:00 | 2023-01-14 16:45:00 | 21 | 1 | 2 | On Time | +| 1003 | 2023-01-15 11:20:00 | 2023-01-18 09:45:00 | 2023-01-22 13:10:00 | 70 | 4 | 7 | Delayed | +| 1004 | 2023-01-16 14:55:00 | 2023-01-17 16:30:00 | 2023-01-21 09:30:00 | 26 | 4 | 5 | Delayed | + +This example demonstrates how `DATEDIFF()` can be used to calculate important business metrics for order processing. The query calculates the processing time in hours, shipping time in days, and total handling time in days. It also identifies delayed shipments based on processing times exceeding 24 hours. + +## Frequently Asked Questions + +### 1. How to calculate date difference between two dates in SQL? + +In SQL Server, use the `DATEDIFF()` function with an appropriate interval parameter like day, month, or year. For example, `DATEDIFF(day, '2023-01-01', '2023-01-15')` will return 14 days. + +### 2. Does `DATEDIFF()` include both the start and end dates in its calculation? + +`DATEDIFF()` counts the number of interval boundaries crossed between the two dates. For example, when using 'day', it counts the number of midnight boundaries crossed, not the full 24-hour periods. + +### 3. Why does `DATEDIFF(year, '2022-12-31', '2023-01-01')` return 1 even though it's just one day apart? + +Because `DATEDIFF()` counts calendar boundaries, not complete intervals. Since the dates span across a year boundary, it returns 1 year, even though the difference is only one day. + +### 4. Does `DATEDIFF()` take time zones into account? + +No, SQL Server's `DATEDIFF()` does not account for time zones or daylight saving time transitions. All calculations are done in the server's local time zone. + +### 5. Can I use `DATEDIFF()` with time-only values? + +Yes, you can use time data types with `DATEDIFF()`, but only with time-related intervals like second, minute, and hour. Using day or larger intervals with time-only values will always return 0. From 9f5c19b395cbdcf9e0abd067a634bc9778ddb33c Mon Sep 17 00:00:00 2001 From: Mamta Wardhani Date: Wed, 21 May 2025 16:09:54 +0530 Subject: [PATCH 2/4] Update datediff.md --- .../concepts/dates/terms/datediff/datediff.md | 191 ++++-------------- 1 file changed, 37 insertions(+), 154 deletions(-) diff --git a/content/sql/concepts/dates/terms/datediff/datediff.md b/content/sql/concepts/dates/terms/datediff/datediff.md index 9426633b080..66f952e9b2e 100644 --- a/content/sql/concepts/dates/terms/datediff/datediff.md +++ b/content/sql/concepts/dates/terms/datediff/datediff.md @@ -1,189 +1,72 @@ --- Title: 'DATEDIFF()' -Description: 'Calculates the difference between two date or timestamp values and returns the result as an integer.' +Description: 'Calculates and returns the difference between two date values. Available in SQL Server and MySQL.' Subjects: - - 'Computer Science' - - 'Web Development' + - 'Data Science' Tags: - 'Database' - 'Date' - - 'Functions' - - 'SQL' + - 'Queries' + - 'MySQL' + - 'SQL Server' CatalogContent: - 'learn-sql' - 'paths/analyze-data-with-sql' + - 'paths/design-databases-with-postgresql' --- -The **`DATEDIFF()`** function calculates the difference between two date or timestamp values and returns the result as an integer in a specified unit of time. This powerful function allows developers and analysts to easily measure time intervals between dates, which is essential for reporting, data analysis, and application development. +**`DATEDIFF()`** is a function found in SQL Server and MySQL that calculates and returns the difference between two date values. -`DATEDIFF()` serves as a cornerstone for date-based calculations in SQL Server, enabling users to perform operations like calculating ages, measuring durations of events, determining time elapsed between transactions, and creating date-based business metrics. Its versatility makes it invaluable for virtually any application that deals with temporal data. - -## Syntax +## SQL Server Syntax ```pseudo -DATEDIFF(interval, date1, date2) +DATEDIFF(datePart, date1, date2) ``` -**Parameters:** - -- `interval`: The time unit in which the difference will be calculated. Valid values include: - - `year`, `yy`, `yyyy`: Years - - `quarter`, `qq`, `q`: Quarters - - `month`, `mm`, `m`: Months - - `dayofyear`, `dy`, `y`: Day of the year - - `day`, `dd`, `d`: Days - - `week`, `wk`, `ww`: Weeks - - `hour`, `hh`: Hours - - `minute`, `mi`, `n`: Minutes - - `second`, `ss`, `s`: Seconds - - `millisecond`, `ms`: Milliseconds - - `microsecond`, `mcs`: Microseconds - - `nanosecond`, `ns`: Nanoseconds -- `date1`: The start date for the calculation. Can be a date, datetime, datetime2, smalldatetime, or time data type, or an expression that resolves to one of these types. -- `date2`: The end date for the calculation. Can be a date, datetime, datetime2, smalldatetime, or time data type, or an expression that resolves to one of these types. - -**Return value:** +The `DATEDIFF()` function in SQL Server has three required parameters: -The `DATEDIFF()` function returns an integer representing the number of time units (specified by the interval parameter) between date1 and date2. +- `datePart` is the part of the date to return. It can be one of the following formats: + - Year: `year`, `yyyy`, `yy` + - Quarter: `quarter`, `qq`, `q` + - Week: `week`, `ww`, `wk` + - Weekday: `weekday`, `dw`, `w` + - Second: `second`, `ss`, `s` + - Month: `month`, `mm`, `m` + - Minute: `minute`, `mi`, `n` + - Millisecond: `millisecond`, `ms` + - Hour: `hour`, `hh` + - Day of Year: `dayofyear` + - Day: `day`, `dy`, `y` +- `date1` and `date2` are the dates to compare. It can be in several formats, one being the `yyyy/mm/dd` format. -## Example 1: Basic Date Difference Calculation +### Example 1 -This example demonstrates how to calculate the difference between two dates in various time intervals: +The following example calculates the difference in months between `2020/05/18` and `2022/05/18`: ```sql --- Calculate difference between two dates in years, months, and days -SELECT - DATEDIFF(year, '2020-01-15', '2023-09-20') AS YearDiff, - DATEDIFF(month, '2020-01-15', '2023-09-20') AS MonthDiff, - DATEDIFF(day, '2020-01-15', '2023-09-20') AS DayDiff; +SELECT DATEDIFF(month, '2020/05/18', '2022/05/18'); /* Output: 24 */ ``` -Output produced by this code will be: - -| YearDiff | MonthDiff | DayDiff | -| -------- | --------- | ------- | -| 3 | 44 | 1344 | - -This example calculates the difference between January 15, 2020, and September 20, 2023, in years, months, and days. The results show there are 3 years, 44 months, or 1344 days between these dates. - -## Example 2: Calculating Age in Years +### Example 2 -This example demonstrates how to use `DATEDIFF()` to calculate a person's age in years from their birthdate. +The following example returns the difference in seconds between `2021/09/30 08:22:04` and `2021/09/30 08:25:06`: ```sql --- Create a sample table with employee data -CREATE TABLE Employees ( - EmployeeID INT PRIMARY KEY, - FirstName VARCHAR(50), - LastName VARCHAR(50), - BirthDate DATE, - HireDate DATE -); - --- Insert sample data -INSERT INTO Employees (EmployeeID, FirstName, LastName, BirthDate, HireDate) -VALUES - (1, 'John', 'Smith', '1985-06-15', '2010-03-20'), - (2, 'Sarah', 'Johnson', '1992-11-30', '2015-07-10'), - (3, 'Michael', 'Brown', '1978-02-23', '2005-09-15'); - --- Calculate ages as of current date -SELECT - EmployeeID, - FirstName + ' ' + LastName AS EmployeeName, - BirthDate, - DATEDIFF(year, BirthDate, GETDATE()) AS Age -FROM - Employees -ORDER BY - Age DESC; +SELECT DATEDIFF(second, '2021/09/30 08:22:04', '2021/09/30 08:25:06'); /* Output: 182 */ ``` -The output generated by this code will be: +## MySQL Syntax -| EmployeeID | EmployeeName | BirthDate | Age | -| ---------- | ------------- | ---------- | --- | -| 3 | Michael Brown | 1978-02-23 | 47 | -| 1 | John Smith | 1985-06-15 | 39 | -| 2 | Sarah Johnson | 1992-11-30 | 32 | +MySQL only requires two date parameters in the `DATEDIFF()` function and will return the number of days between `date1` and `date2`. -This example shows how to calculate an employee's age by finding the difference in years between their birthdate and the current date. Note that this calculation provides the raw year difference and doesn't account for whether the birthday has occurred yet in the current year. +```pseudo +DATEDIFF(date1, date2) +``` -## Example 3: Business Metrics with `DATEDIFF()` +### Example -This example demonstrates how to use `DATEDIFF()` for business reporting metrics, such as calculating order processing times and identifying delayed shipments. +The following example returns the difference in days between `2019-07-05` and `2018-12-24`: ```sql --- Create sample orders table -CREATE TABLE Orders ( - OrderID INT PRIMARY KEY, - CustomerID INT, - OrderDate DATETIME, - ShipDate DATETIME, - DeliveryDate DATETIME -); - --- Insert sample data -INSERT INTO Orders (OrderID, CustomerID, OrderDate, ShipDate, DeliveryDate) -VALUES - (1001, 101, '2023-01-10 09:30:00', '2023-01-11 14:15:00', '2023-01-15 11:20:00'), - (1002, 102, '2023-01-12 13:45:00', '2023-01-13 10:30:00', '2023-01-14 16:45:00'), - (1003, 103, '2023-01-15 11:20:00', '2023-01-18 09:45:00', '2023-01-22 13:10:00'), - (1004, 104, '2023-01-16 14:55:00', '2023-01-17 16:30:00', '2023-01-21 09:30:00'), - (1005, 105, '2023-01-18 10:15:00', NULL, NULL); - --- Calculate processing, shipping, and total handling times -SELECT - OrderID, - OrderDate, - ShipDate, - DeliveryDate, - -- Processing time (from order to shipment) - DATEDIFF(hour, OrderDate, ShipDate) AS ProcessingHours, - -- Shipping time (from shipment to delivery) - DATEDIFF(day, ShipDate, DeliveryDate) AS ShippingDays, - -- Total time (from order to delivery) - DATEDIFF(day, OrderDate, DeliveryDate) AS TotalDays, - -- Identify delayed shipments (processing > 24 hours) - CASE - WHEN DATEDIFF(hour, OrderDate, ShipDate) > 24 THEN 'Delayed' - ELSE 'On Time' - END AS ShipmentStatus -FROM - Orders -WHERE - ShipDate IS NOT NULL; +SELECT DATEDIFF("2019-07-05", "2018-12-24"); /* Output: 193 */ ``` - -The output of this code will be: - -| OrderID | OrderDate | ShipDate | DeliveryDate | ProcessingHours | ShippingDays | TotalDays | ShipmentStatus | -| ------- | ------------------- | ------------------- | ------------------- | --------------- | ------------ | --------- | -------------- | -| 1001 | 2023-01-10 09:30:00 | 2023-01-11 14:15:00 | 2023-01-15 11:20:00 | 29 | 4 | 5 | Delayed | -| 1002 | 2023-01-12 13:45:00 | 2023-01-13 10:30:00 | 2023-01-14 16:45:00 | 21 | 1 | 2 | On Time | -| 1003 | 2023-01-15 11:20:00 | 2023-01-18 09:45:00 | 2023-01-22 13:10:00 | 70 | 4 | 7 | Delayed | -| 1004 | 2023-01-16 14:55:00 | 2023-01-17 16:30:00 | 2023-01-21 09:30:00 | 26 | 4 | 5 | Delayed | - -This example demonstrates how `DATEDIFF()` can be used to calculate important business metrics for order processing. The query calculates the processing time in hours, shipping time in days, and total handling time in days. It also identifies delayed shipments based on processing times exceeding 24 hours. - -## Frequently Asked Questions - -### 1. How to calculate date difference between two dates in SQL? - -In SQL Server, use the `DATEDIFF()` function with an appropriate interval parameter like day, month, or year. For example, `DATEDIFF(day, '2023-01-01', '2023-01-15')` will return 14 days. - -### 2. Does `DATEDIFF()` include both the start and end dates in its calculation? - -`DATEDIFF()` counts the number of interval boundaries crossed between the two dates. For example, when using 'day', it counts the number of midnight boundaries crossed, not the full 24-hour periods. - -### 3. Why does `DATEDIFF(year, '2022-12-31', '2023-01-01')` return 1 even though it's just one day apart? - -Because `DATEDIFF()` counts calendar boundaries, not complete intervals. Since the dates span across a year boundary, it returns 1 year, even though the difference is only one day. - -### 4. Does `DATEDIFF()` take time zones into account? - -No, SQL Server's `DATEDIFF()` does not account for time zones or daylight saving time transitions. All calculations are done in the server's local time zone. - -### 5. Can I use `DATEDIFF()` with time-only values? - -Yes, you can use time data types with `DATEDIFF()`, but only with time-related intervals like second, minute, and hour. Using day or larger intervals with time-only values will always return 0. From dd1ef4a5c6cd119087e687e43b39cff366631fa6 Mon Sep 17 00:00:00 2001 From: Mamta Wardhani Date: Wed, 18 Jun 2025 15:52:34 +0530 Subject: [PATCH 3/4] [Edit] SwiftUI: UIKit --- content/swiftui/concepts/uikit/uikit.md | 198 +++++++++++++++++++++++- 1 file changed, 190 insertions(+), 8 deletions(-) diff --git a/content/swiftui/concepts/uikit/uikit.md b/content/swiftui/concepts/uikit/uikit.md index a5dbb7038a1..ff6a7a254d3 100644 --- a/content/swiftui/concepts/uikit/uikit.md +++ b/content/swiftui/concepts/uikit/uikit.md @@ -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, 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. From 22569e94e55cf152768cacf9067672091b16c2e9 Mon Sep 17 00:00:00 2001 From: Mamta Wardhani Date: Wed, 18 Jun 2025 16:30:21 +0530 Subject: [PATCH 4/4] [Edit] General: heap sort --- .../algorithm/terms/heap-sort/heap-sort.md | 59 +++++++++++++++---- 1 file changed, 47 insertions(+), 12 deletions(-) diff --git a/content/general/concepts/algorithm/terms/heap-sort/heap-sort.md b/content/general/concepts/algorithm/terms/heap-sort/heap-sort.md index 56b52dea00b..eaf5ae83668 100644 --- a/content/general/concepts/algorithm/terms/heap-sort/heap-sort.md +++ b/content/general/concepts/algorithm/terms/heap-sort/heap-sort.md @@ -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`. @@ -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:** @@ -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.