Sorting Array Elements
Given an array of integers, sort them in ascending order and return the sorted array. The smallest value should come first, and the largest value should come last.
For example, sorting [4, 1, 3, 2] produces [1, 2, 3, 4]. Sorting [5] produces [5]. Sorting an empty array produces []. Negative numbers and duplicates are handled naturally — negatives come first, duplicates remain.
Sorting is one of the most fundamental operations in computer science. It is the foundation for binary search, data analysis, and efficient algorithms that require ordered data. While production systems use optimized sorting algorithms, this problem tests your understanding of the sorting concept.
The simplest approach uses a built-in sort function with a numeric comparator. The comparator ensures numbers are sorted numerically rather than as strings. Most languages provide O(n log n) sorting as a built-in operation.
Edge cases include an empty array (return []), a single element (return the same), all equal values (return the same array), and arrays with negative values (sorted correctly before positive values).
Algorithm Flow
Solution Approach
Use the built-in sort function with a numeric comparator to sort elements from smallest to largest.
Return a new array containing all elements of the input sorted in ascending order. The sort function rearranges elements so that the smallest value is at the first position and the largest at the last. For correct numeric ordering, the comparator must use numeric comparison rather than the default string comparison.
Time complexity is O(n log n) for efficient comparison-based sorting. Space complexity is O(n) for the new sorted array.
Best Answers
program sort_data
dictionary
n, i, j, min_idx, temp: integer
arr: array[1..100] of integer
algorithm
input(n)
for i <- 1 to n do input(arr[i]) endfor
for i <- 1 to n - 1 do
min_idx <- i
for j <- i + 1 to n do
if arr[j] < arr[min_idx] then min_idx <- j endif
endfor
temp <- arr[i]
arr[i] <- arr[min_idx]
arr[min_idx] <- temp
endfor
for i <- 1 to n do output(arr[i]) endfor
endprogramComments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
