Post

Created by @nathanedwards
 at October 31st 2023, 9:21:20 pm.

Question:

Consider the following array of integers: [9, 2, 7, 4, 5, 6].

Write a code snippet in Java that implements the selection sort algorithm to sort the array in ascending order. Your implementation should use the selection sort algorithm and update the array in-place.

Provide the complete code implementation in the answer section below. Make sure to include any necessary variable declarations or imports.

Answer:

public class SelectionSort {
    
    public static void selectionSort(int[] arr) {
        int n = arr.length; 
        
        for (int i = 0; i < n-1; i++) {
            int minIndex = i;
            
            for (int j = i+1; j < n; j++) {
                if (arr[j] < arr[minIndex]) {
                    minIndex = j;
                }
            }
            
            swap(arr, i, minIndex);
        }
    }
    
    public static void swap(int[] arr, int i, int j) {
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }
    
    public static void main(String[] args) {
        int[] arr = {9, 2, 7, 4, 5, 6};
        
        System.out.println("Original array: " + Arrays.toString(arr));
        
        selectionSort(arr);
        
        System.out.println("Sorted array: " + Arrays.toString(arr));
    }
}

Explanation:

The selection sort algorithm works by iteratively dividing the array into two subarrays: the sorted left portion and the unsorted right portion. At each iteration, the algorithm selects the smallest element from the unsorted portion and swaps it with the first element in the unsorted portion.

In the provided code snippet, the selectionSort method implements the selection sort algorithm. The outer loop iterates from the first element to the second-to-last element of the array. For each iteration, it initializes a minIndex variable to keep track of the index of the smallest element seen so far, starting from i.

The inner loop starts from i+1 and compares each subsequent element to the element at the minIndex. If a smaller element is found, the minIndex is updated.

After the inner loop completes, the swap method is called to swap the element at i with the smallest element found (arr[minIndex]). This effectively places the smallest element in its correct position in the sorted left portion of the array.

Finally, the main method demonstrates the usage of the selectionSort method by applying it to the provided array. The original and sorted arrays are then printed using the Arrays.toString() method for verification.

The resulting output of the code snippet would be:

Original array: [9, 2, 7, 4, 5, 6]
Sorted array: [2, 4, 5, 6, 7, 9]

Note: The Arrays.toString() method is used to convert the array to a string representation for printing. Don't forget to import the java.util.Arrays class at the top of your code.