Post

Created by @nathanedwards
 at October 31st 2023, 2:10:54 pm.

Question:

Consider the following array of integers:

int[] numbers = {5, 2, 9, 1, 3};

Write a Java method selectionSort to sort the given array in ascending order using the selection sort algorithm. Your method should take in an integer array as a parameter and return the sorted array.

Signature:

public static int[] selectionSort(int[] arr)

Example:

Input:

int[] numbers = {5, 2, 9, 1, 3};
int[] sortedNumbers = selectionSort(numbers);

Output:

[1, 2, 3, 5, 9]

Explanation:

The selection sort algorithm works by dividing the array into two parts: sorted and unsorted. Initially, the sorted part is empty, and the unsorted part consists of the entire array. The algorithm then repeatedly selects the minimum element from the unsorted part and swaps it with the first element of the unsorted part. This process is repeated until the entire array is sorted.

Here's a step-by-step explanation of the selection sort algorithm with the given example array [5, 2, 9, 1, 3]:

  1. Find the minimum element (1) in the unsorted part of the array [5, 2, 9, 1, 3] and swap it with the first element (5) of the unsorted part. The array becomes [1, 2, 9, 5, 3].
  2. Find the minimum element (2) in the remaining unsorted part of the array [2, 9, 5, 3] and swap it with the first element (2) of the unsorted part. The array remains the same.
  3. Find the minimum element (3) in the remaining unsorted part of the array [9, 5, 3] and swap it with the first element (9) of the unsorted part. The array becomes [3, 5, 9].
  4. Find the minimum element (5) in the remaining unsorted part of the array [5, 9] and swap it with the first element (5) of the unsorted part. The array remains the same.
  5. Find the minimum element (9) in the remaining unsorted part of the array [9] and swap it with the first element (9) of the unsorted part. The array remains the same.

The array is now sorted in ascending order: [1, 2, 3, 5, 9].

Note: The selection sort algorithm has an average and worst-case time complexity of O(n^2), where n is the number of elements in the array.