Swift Coding Test Course, Sorting Numbers 2

In this post, we will discuss sorting problems that are frequently presented in coding tests using Swift. In particular, we will explore the basics of sorting algorithms through the “Sorting Numbers 2” problem and how it can be applied in actual coding tests.

Problem Description

Sort the given array of N numbers in ascending order and print the result. N is a natural number less than or equal to 1,000,000, and each number in the array is an integer that is less than or equal to 1,000,000 and greater than or equal to 0.

Input: 
    5
    5
    4
    3
    2
    1

    Output: 
    1
    2
    3
    4
    5

Problem-Solving Approach

This problem requires an understanding and implementation of basic sorting algorithms. However, considering the limited time and memory, we need to perform the sorting in the most efficient way. Generally, we can consider quick sort, merge sort, or heap sort, which have a time complexity of O(N log N), but since the range of numbers is limited in this problem, it is efficient to use counting sort.

Counting Sort

Counting sort is useful when the range of data to be sorted is limited. Given that the range of numbers is from 0 to 1,000,000 and duplicates may exist, we can count the occurrences of each number to generate the sorted result. Counting sort follows these steps:

  1. Check the maximum value of the input numbers to determine the size of the array.
  2. Initialize a counting array with indices from 0 to the maximum value.
  3. Read the input numbers and increment the corresponding index in the counting array by 1.
  4. Refer to the counting array to output the sorted result.

Swift Implementation

Now, let’s write the code in Swift based on the above approach.

import Foundation

let n = Int(readLine()!)!
var numbers = [Int](repeating: 0, count: 1000001)

// Store input values
for _ in 0.. 0 {
        for _ in 0..

Code Explanation

Let’s explain the above code:

  1. On the first line, `let n = Int(readLine()!)!` reads the number of inputs.
  2. `var numbers = [Int](repeating: 0, count: 1000001)` creates a counting array to store numbers from 0 to 1,000,000.
  3. Through the loop `for _ in 0..
  4. Finally, we traverse the counting array through a nested loop and output the results based on how many times each number appeared.

Complexity Analysis

The time complexity of this problem is O(N), and the space complexity is O(K) (where K is the range of input numbers, specifically 1,000,001). Therefore, it can handle a large number of inputs efficiently.

Conclusion

In this post, we explored how to solve the "Sorting Numbers 2" problem using counting sort. Counting sort is very useful when the range of data is limited, so keep this in mind. Increasing your understanding of various sorting algorithms can help reduce time and improve your coding quality. In the next post, we will cover another algorithm problem!