TypeScript: Sort an Array of Numbers

1. Introduction

Sorting is one of the fundamental operations in computer science. Whether you're organizing data or performing complex algorithms, sorting often plays a critical role. In this post, we'll walk through a TypeScript program that sorts an array of numbers.

2. Program Overview

We will define a function named sortNumbers that takes an array of numbers as an argument. This function will then return a new array with the numbers sorted in ascending order. We'll use the built-in sort() method available on arrays in TypeScript and JavaScript.

3. Code Program

// Function to sort an array of numbers
function sortNumbers(numbers: number[]): number[] {
    // Sort the array and return
    return numbers.sort((a, b) => a - b);
}

// Test the function
const numbers = [5, 2, 9, 1, 5, 6];
console.log(`Original array: [${numbers}]`);
console.log(`Sorted array: [${sortNumbers(numbers)}]`);

Output:

Original array: [5, 2, 9, 1, 5, 6]
Sorted array: [1, 2, 5, 5, 6, 9]

4. Step By Step Explanation

1. We begin by defining our function sortNumbers which accepts an array of numbers named numbers as its argument.

2. Inside the function, we use the sort() method provided by the Array prototype. However, for numbers, we need to provide a comparison function to sort correctly. This is because, by default, the sort() method sorts elements as strings.

3. The comparison function (a, b) => a - b is used to dictate the order of sorting. If the result is less than 0, a comes before b. If the result is 0, their order remains unchanged. If the result is greater than 0, b comes before a.

4. By using this comparison function, our array of numbers gets sorted in ascending order.

5. Finally, we test our function using a sample array of numbers and print both the original and sorted arrays.

Comments