Question

Java : Modify the selection sort algorithm to sort an array of integers in descending order....

Java : Modify the selection sort algorithm to sort an array of integers in descending order. describe how the skills you have gained could be applied in the field.

Please don't use an already answered solution from chegg. I've unfortunately had that happen at many occasion

.......

........

sec01/SelectionSortDemo.java

import java.util.Arrays;

/**
This program demonstrates the selection sort algorithm by
sorting an array that is filled with random numbers.
*/
public class SelectionSortDemo
{
public static void main(String[] args)
{
int[] a = ArrayUtil.randomIntArray(20, 100);
System.out.println(Arrays.toString(a));

SelectionSorter.sort(a);

System.out.println(Arrays.toString(a));
}
}

sec01/ArrayUtil.java

import java.util.Random;

/**
This class contains utility methods for array manipulation.
*/
public class ArrayUtil
{
private static Random generator = new Random();

/**
Creates an array filled with random values.
@param length the length of the array
@param n the number of possible random values
@return an array filled with length numbers between
0 and n - 1
*/
public static int[] randomIntArray(int length, int n)
{
int[] a = new int[length];
for (int i = 0; i < a.length; i++)
{
a[i] = generator.nextInt(n);
}
  
return a;
}

/**
Swaps two entries of an array.
@param a the array
@param i the first position to swap
@param j the second position to swap
*/
public static void swap(int[] a, int i, int j)
{
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}

sec01/SelectionSorter.java

/**
The sort method of this class sorts an array, using the selection
sort algorithm.
*/
public class SelectionSorter
{
/**
Sorts an array, using selection sort.
@param a the array to sort
*/
public static void sort(int[] a)
{
for (int i = 0; i < a.length - 1; i++)
{
int minPos = minimumPosition(a, i);
ArrayUtil.swap(a, minPos, i);
}
}

/**
Finds the smallest element in a tail range of the array.
@param a the array to sort
@param from the first position in a to compare
@return the position of the smallest element in the
range a[from] . . . a[a.length - 1]
*/
private static int minimumPosition(int[] a, int from)
{
int minPos = from;
for (int i = from + 1; i < a.length; i++)
{
if (a[i] < a[minPos]) { minPos = i; }
}
return minPos;
}
}

Extra Note: Let’s program this algorithm, called selection sort. For this program, as well as the other programs in this chapter, we will use a utility method to generate an array with random entries. We place it into a class ArrayUtil so that we don’t have to repeat the code in every example. To show the array, we call the static toString method of the Arrays class in the Java library and print the resulting string (see Section 7.3.4). We also add a method for swapping elements to the ArrayUtil class. (See Section 7.3.8 for details about swapping array elements.)

This algorithm will sort any array of integers. If speed were not an issue, or if there were no better sorting method available, we could stop the discussion of sorting right here. As the next section shows, however, this algorithm, while entirely correct, shows disappointing performance when run on a large data set.

Special Topic 14.2 discusses insertion sort, another simple sorting algorithm.

Homework Answers

Answer #1

Explanation: As you have mentioned please do not already answered solution,we cannot see others answers.I have modified the SelectionSorter.java and in that instead of finding the minimumPosition find the maximumPostition in the array which can be done by changing the method minimumPosition to maximumPostition and then place it at the 0th position in the array, similarly for all the numbers this process is carried out and we get the resulting array in the descending order.The algorithm selection sort works by swapping the largest number at the first position from the array and thus for each iteration this process continues and we get the desired result.If you want some other approach or method please mention in the comments, i will modify the code accordingly.lease upvote if you liked my answer and comment if you need any modification or explanation.

/**
* The sort method of this class sorts an array, using the selection sort
* algorithm.
*/
public class SelectionSorter
{
   /**
   * Sorts an array, using selection sort.
   *
   * @param a the array to sort
   */
   public static void sort(int[] a)
   {
       for (int i = 0; i < a.length - 1; i++)
       {
           int maxPos = maximumPosition(a, i);
           ArrayUtil.swap(a, i, maxPos);
       }
   }

   /**
   * Finds the largest element in a tail range of the array.
   *
   * @param a the array to sort
   * @param from the first position in a to compare
   * @return the position of the largest element in the range a[from] . . .
   * a[a.length - 1]
   */
   private static int maximumPosition(int[] a, int from)
   {
       int maxPos = from;
       for (int i = from + 1; i < a.length; i++)
       {
           if (a[i] > a[maxPos])
           {
               maxPos = i;
           }
       }
       return maxPos;
   }
}

Output:

Know the answer?
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for?
Ask your own homework help question
Similar Questions
Hi. I want to make this cocktail sort method, but with the call sort(Comparable[] array). What...
Hi. I want to make this cocktail sort method, but with the call sort(Comparable[] array). What changes do I have to make, and how will the end result be? public class CocktailSort { public static void sort(Integer[] array) { int start = -1; int end = array.length - 2; boolean swapped; do { swapped = false; for (int i = ++start; i <= end; i++) { if (array[i] > array[i + 1]) { swap(array, i, i + 1); swapped =...
First, understand the Selection-sort algorithm below: Selection-sort(A: Array [1..n] of numbers) 1       for i=n down to...
First, understand the Selection-sort algorithm below: Selection-sort(A: Array [1..n] of numbers) 1       for i=n down to 2 2                position=i 3                for j=1 to (i–1) 4                          if A[j]>A[position] then position=j 5                if position ≠ i then 6                          temp=A[i] 7                          A[i]=A[position] 8                          A[position]=temp (4 points) If input A=[12,5,11,6,10,7,9,8], what will A be after the 3rd iteration of the outermost for loop of the Selection-sort algorithm completes? A=[__, __, __, __, __, __, __, __] (8 points) Modify the algorithm to solve the...
Complete the java code as per the comments public class Sorting {    ///////////////////////////////////////////////    //...
Complete the java code as per the comments public class Sorting {    ///////////////////////////////////////////////    // STEP 1 -- Make sorting methods generic    ///////////////////////////////////////////////       /**    * Re-orders the contents given array using the insertion sort algorithm.    *    * @param data The array to be sorted.    */    //TODO: Make me generic to work on any kind of Comparable data!    public static void insertionSort(int[] data)    {        int insert; // temporary...
Finish the code wherever it says TODO /**    * Node type for this list. Each...
Finish the code wherever it says TODO /**    * Node type for this list. Each node holds a maximum of nodeSize elements in an    * array. Empty slots are null.    */    private class Node {        /**        * Array of actual data elements.        */        // Unchecked warning unavoidable.        public E[] data = (E[]) new Comparable[nodeSize];        /**        * Link to next node.       ...
Implement functions for insertion sort, quicksort, heapsort and merge sort that input an array of integers...
Implement functions for insertion sort, quicksort, heapsort and merge sort that input an array of integers and sort it in-place. Write a program that generates random integer arrays (hint: use seed appropriately to avoid generating same sequences) of lengths 10, 100, 1000, 10,000, 100,000, 1000,000, and then sorts each using each of the sorting functions from (a), and measures the time in nanoseconds. The program will repeat this process 30 times and will compute the average execution time for each...
Write a Java program that asks the user to enter an array of integers in the...
Write a Java program that asks the user to enter an array of integers in the main method. The program should prompt the user for the number of elements in the array and then the elements of the array. The program should then call a method named isSorted that accepts an array of and returns true if the list is in sorted (increasing) order and false otherwise. For example, if arrays named arr1 and arr2 store [10, 20, 30, 41,...
Write a MIPS assembly program that sorts an array using bubble sort translating the C code...
Write a MIPS assembly program that sorts an array using bubble sort translating the C code int main(void) { int array[] = {10, 2, 7, 5, 15, 30, 8, 6}; // input array int arraySize = sizeof(array)/sizeof(array[0]); bool swapped = true; int j = 0; int tmp; while (swapped) { swapped = false; //Note : "j" , "arraySize - j" are optimizations to the bubble sort algorithm j++; // j= sorted elements int i=0; /* "arraySize - j" is used...
. A sorting algorithm is stable if the relative order of any two equal entries in...
. A sorting algorithm is stable if the relative order of any two equal entries in the given array stays the same: when two records a[i] and a[j] are equal in content, and i < j, then the algorithm sorts the array in a way that the record originally stored in a[i], still appears to the left of the record originally stored in a[j], when the array is sorted. Which of the algorithms Insertion Sort, Shellsort, Heapsort, and Mergesort (as...
Problem 3 (4 marks). A sorting algorithm is stable if the relative order of any two...
Problem 3 . A sorting algorithm is stable if the relative order of any two equal entries in the given array stays the same: when two records a[i] and a[j] are equal in content, and i < j, then the algorithm sorts the array in a way that the record originally stored in a[i], still appears to the left of the record originally stored in a[j], when the array is sorted. Which of the algorithms Insertion Sort, Shellsort, Heapsort, and...
Problem 3 (4 marks). A sorting algorithm is stable if the relative order of any two...
Problem 3 . A sorting algorithm is stable if the relative order of any two equal entries in the given array stays the same: when two records a[i] and a[j] are equal in content, and i < j, then the algorithm sorts the array in a way that the record originally stored in a[i], still appears to the left of the record originally stored in a[j], when the array is sorted. Which of the algorithms Insertion Sort, Shellsort, Heapsort, and...
ADVERTISEMENT
Need Online Homework Help?

Get Answers For Free
Most questions answered within 1 hours.

Ask a Question
ADVERTISEMENT