Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a Java program in which the recursive version of the selection sorting met

ID: 3864645 • Letter: W

Question

Write a Java program in which the recursive version of the selection sorting method with the following signature:

public static void r_selectionSort(int[ ] array, int s, int t)

should be defined. That method arranges a collection of integers in an integer array with beginning index s and terminating index t in ascending order. Your program will ask the user to input a positive integer for the size of an integer array, fill in the array with integers between 0 and 999 inclusively, display the integers in the array, invoke the method r_selectionSort, and display the integers in the array again. A sample run of your program is as follows.

Input an integer for the size of an array:

16

16 numbers are generated and they are:

922 602 519 429 776 924 167 941 629 115 842 620 464 31 209 753

16 numbers are sorted by recursive selection-sorting program and they are:

31 115 167 209 429 464 519 602 620 629 753 776 842 922 924 941

Explanation / Answer

Java Code:

import java.util.Scanner;
import java.util.Random;
public class RecursiveSelectionSort{
  

public static int[] r_selectionSort(int[] array,int s,int t){
int temp;
if(s>=t){ //if s=t then all the numbers from s to t
//are sorted therefore return
return array;
}else{
for(int i=s;i<=t;i++){// else swap the element at s with minimum number
//in the range s to t
if(array[i]<array[s]){
temp=array[s];
array[s]=array[i];
array[i]=temp;
}
}
  
return r_selectionSort(array,++s,t);//increment s. call again to sort numbers in range s+1 to t
}
}

public static void main(String []args){
Scanner in=new Scanner(System.in);
Random rand=new Random();
System.out.println("Input an integer for the size of an array:");
int size=in.nextInt(); //read in size of array
int[] array=new int[size];//declare array of size 'size'
  
for(int i=0;i<size;i++){//initialize array with random numbers in the range [0,999]
array[i]=rand.nextInt(999);   
}
System.out.println(size+" numbers are generated and they are:"); //print;
for(int i=0;i<size;i++){
System.out.print(array[i]+" ");
}

array=r_selectionSort(array,0,size-1); //sort the entire array ie from 0 to size-1
System.out.println(" "+size+" numbers are sorted by recursive selection-sorting program and they are:");
for(int i=0;i<size;i++){//print result
System.out.print(array[i]+" ");
}
System.out.println();
}
}

NOTE: Copy the code to file named RecursiveSelectionSort.java. Compile and Run

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote