Tutorialspoint
Problem
Solution
Submissions

Sort an Array of Integers

Certification: Basic Level Accuracy: 66.67% Submissions: 9 Points: 5

Write a C++ function to sort an array of integers in ascending order.

Example 1
  • Input: array = [5, 3, 8, 1]
  • Output: [1, 3, 5, 8]
  • Explanation:
    • Step 1: Compare and swap elements to sort them in ascending order.
    • Step 2: Rearrange the array through multiple passes.
    • Step 3: Return the sorted array.
Example 2
  • Input: array = [10, 2, 7, 4]
  • Output: [2, 4, 7, 10]
  • Explanation:
    • Step 1: Compare and swap elements to sort them in ascending order.
    • Step 2: Rearrange the array through multiple passes.
    • Step 3: Return the sorted array [2, 4, 7, 10].
Constraints
  • 1 ≤ array length ≤ 10^4
  • -10^5 ≤ array elements ≤ 10^5
  • Time Complexity: O(n log n)
  • Space Complexity: O(1)
NumberAlgorithmsIBMKPMG
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use a sorting algorithm like quicksort or mergesort.
  • You can also use the built-in sort function from the C++ STL.
  • Ensure the function works for the upper limit of the constraint.

Steps to solve by this approach:

 Step 1: Define a function sort_array that takes a vector of integers.
 Step 2: Use the standard sort function from the algorithm library.
 Step 3: Sort the array in ascending order using begin and end iterators.
 Step 4: Return the sorted array.
 Step 5: In main, call sort_array with a vector of values.
 Step 6: Loop through the sorted array and print the elements.

Submitted Code :