Q1:Write one method called sortArray (Java) that takes one unsorted integer arra
ID: 639514 • Letter: Q
Question
Q1:Write one method called sortArray (Java) that takes one unsorted integer array as input (has one parameter) and returns another sorted integer array (is a value method). Use the selection sort algorithm.
Q2:Write a Java console application that prompts the user for six integers, stores them in an array, sorts the array into a new array, and prints the values stored in both arrays side-by-side. Use the sortArray method created in Question 1. Output should have this format:
Index Unsorted array Sorted array
0 3 2
1 2 3
2 11 4
3 4 7
4 10 10
5 7 11
Explanation / Answer
Sample Run:
Enter six integers
3
2
11
4
10
7
index unsorted array sorted array
0 3 2
1 2 3
2 11 4
3 4 7
4 10 10
5 7 11
Required Solution for the question 1 and 2
import java.util.Scanner;
public class SelectionSort
{
public static void sortArray(int[] arr)//solution for question 1
{
for (int i = 0; i < arr.length - 1; i++)
{
int index = i; for (int j = i + 1; j < arr.length; j++)
if (arr[j] < arr[index]) index = j;
int smallerNumber = arr[index];
arr[index] = arr[i]; arr[i] = smallerNumber;
}
}
public static void main(String a[])
{
int[] arr1 = new int[6];
int[] arr2=new int[6];
System.out.println("Enter six integers");
Scanner sc=new Scanner(System.in);
for(int i=0;i<6;i++)
arr1[i]=arr2[i]=sc.nextInt();
sortArray(arr2);
System.out.println("index unsorted array sorted array");
for(int i=0;i<arr1.length;i++)
{
System.out.print(i+" "+arr1[i]+" "+arr2[i]);
System.out.println();
}
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.