Problem with implementing bi-directional selection sort - java

I am trying to implement bi-directional selection sort(double selection sort).
A double-selection sort finds both the smallest and largest elements during its scan, and swaps the smallest into the first position, and the largest into the last position. The algorithm then proceeds looking at all the elements between the first and last.
I am able to get the logic required to perform the task.But,i think i am doing something wrong with comparing variables or maybe implementing comparable properly.
public void sort(T[] input) {
for(int i=0; i<input.length -1; i++){
int min = i;
int max = i;
for(int j=i+1; j<input.length; j++){
if(input[min].compareTo((input[j])) > 0 )
{
min = j;
T swap = input[min];
input[min] = input[i];
input[i] = swap;
}
}
for(int k=i+1; k<input.length; k++){
if(input[max].compareTo((input[k])) < 0 )
{
max = k;
T swap = input[max];
input[max] = input[i];
input[i] = swap;
}
}
}
}
///// Test File
/** Returns true if the input array is ordered (every element ≤
* the following one.)
*
* #param data Array to check
* #return True if array is ordered
*/
boolean isOrdered(Integer[] data) {
for(int i = 0; i < data.length - 1; ++i)
if(data[i] > data[i+1])
return false;
return true;
}
/** Counts the number of times x occurs in the array in.
*
* #param in Array
* #param x Element to count
* #return Count of x's in the array
*/
int countElement(Integer[] in, Integer x) {
int c = 0;
for(int i : in)
if(i == x)
c++;
return c;
}
/** Returns true if both arrays contain the same elements,
* disregarding order (i.e., is one a permutation of the other).
* #param in Unsorted array
* #param out Potentially-sorted array to check
* #return True if out is a permutation of in
*/
boolean sameElements(Integer[] in, Integer[] out) {
for(Integer i : in)
if(countElement(in,i) != countElement(out,i))
return false;
return true;
}
/** Creates an array of the given size filled with random values.
*
* #param size Size of the resulting array
* #return Array of random values
*/
Integer[] randomArray(int size) {
Integer[] arr = new Integer[size];
for(int i = 0; i < size; ++i)
arr[i] = Math.round((float)Math.random() * Integer.MAX_VALUE);
return arr;
}
/** Tests the DoubleSelectionSort dss against the unsorted data.
*
* #param dss Sorter to use
* #param data Array to sort and check
*/
void testSort(DoubleSelectionSort dss, Integer[] data) {
Integer[] sorted = Arrays.copyOf(data, data.length);
dss.sort(sorted);
assertTrue("Result of sort is not sorted in order", isOrdered(sorted));
assertTrue("Result of sort has different elements from input", sameElements(data, sorted));
}
#Test
public void testSort() {
System.out.println("sort");
DoubleSelectionSort<Integer> dss = new DoubleSelectionSort<>();
// Test on arrays size 0 to 100
for(int i = 0; i <= 100; ++i)
testSort(dss, randomArray(i));
}
}
testSort Failed : Result of Sort is not sorted in order

It seems that you are using wrong conditions in Sorting Logic of Selection Sort.
I have given here example of Selection Sort function with generic type. Please have a look at this:
public static <E extends Comparable<E>> void selectionSort(E[] list)
{
for(int i=0; i<list.length -1; i++)
{
int iSmall = i;
for(int j=i+1; j<list.length; j++)
{
if(list[iSmall].compareTo((list[j])) > 0 )
{
iSmall = j;
}
}
E iSwap = list[iSmall];
list[iSmall] = list[i];
list[i] = iSwap;
}
}

Related

Check if number exist in a row and a column in a Bidimensional Array Java

I'm trying to make a program that generates ramdom sudokus.
The program verifies that a number is not repeated in the row and in the column,
verifyExistNumberInRow --> works perfect
But when call to verifyExistNumberInColumn --> infinite loop
Why, I dont found the solution, is an index problem? or a value problem?.
Thank you.
/**
* Generate a random Sudoku
*/
private static void generateRandomSudoku() {
Integer[][] array = new Integer[9][9];
Integer number;
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
do {
number = (int) (Math.random() * 9) + 1;
} while (verifyExistNumberInRow(number, array[i]) || verifyExistNumberInColumn(j, number, array));
array[i][j] = number;
}
}
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
System.out.print(array[i][j] + " ");
}
System.out.print("\n");
}
}
/**
* Check if a number exist in array file.
*
* #param number
* #param array
* #return True if exist, other false.
*/
private static boolean verifyExistNumberInRow(Integer number, Integer[] array) {
return Stream.of(array)
.filter(Objects::nonNull)
.anyMatch(element -> element.equals(number));
}
/**
* Check if a number exist in array column
*
* #param position column number
* #param number number to find in column
* #param array
* #return true if exist, other false
*/
private static boolean verifyExistNumberInColumn(Integer position, Integer number, Integer[][] array) {
for (int i = 0; i < array.length; i++) {
if (array[i][position] != null) {
if (array[i][position].equals(number)) {
return true;
}
}
}
return false;
}
Try reverse the location of 'position' and 'i' and add "i < array[position].length":
private static boolean verifyExistNumberInColumn(Integer position, Integer number, Integer[][] array) {
for (int i = 0; i < array[position].length; i++) {
if (array[position][i] != null) {
if (array[position][i].equals(number)) {
return true;
}
}
}
return false;
}
The solution that i find is deleted the row when number is found in column. And works it.
private static void generateRandomSudoku() {
Integer[][] array = new Integer[9][9];
Integer number;
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
boolean found = true;
while (found) {
number = (int) (Math.random() * 9) + 1;
if (!verifyExistNumberInRow(number, array[i])) {
if (!verifyExistNumberInColumn(j, number, array)) {
array[i][j] = number;
found = false;
} else {
array = deleteRow(i, array);
j = 0;
}
}
}
}
}
printSudoku(array);
}
/**
* Delete (set to null) values for a row from bidimensional array
*
* #param row row number to delete
* #param array
* #return
*/
private static Integer[][] deleteRow(int row, Integer[][] array) {
for (int i = 0; i < array.length; i++) {
array[row][i] = null;
}
return array;
}
/**
* Check if a number exist in array file.
*
* #param number
* #param array
* #return True if exist, other false.
*/
private static boolean verifyExistNumberInRow(Integer number, Integer[] array) {
return Stream.of(array)
.filter(Objects::nonNull)
.anyMatch(element -> element.equals(number));
}
/**
* Check if a number exist in array column
*
* #param position column number
* #param number number to find in column
* #param array
* #return true if exist, other false
*/
private static boolean verifyExistNumberInColumn(Integer position, Integer number, Integer[][] array) {
for (int i = 0; i < array[position].length; i++) {
if (array[i][position] != null) {
if (array[i][position].equals(number)) {
return true;
}
}
}
return false;
}

Trying to reduce Radix Sort program execution time (Java)

I have created an implementation of radixsort using ArrayLists of integer arrays. The code is functional however as input size increases passed about 100,000 execution time is far too high. I need this code to be able to handle an input of 1,000,000 integers. What can I do to optimize execution time?
public class RadixSort {
public static void main(String[] args) {
// generate and store 1,000,000 random numbers
int[] nums = generateNums(1000000);
// sort the random numbers
int[] sortedNums = radixSort(nums);
// check that the array was correctly sorted and print result
boolean sorted = isSorted(sortedNums);
if (sorted) {
System.out.println("Integer list is sorted");
} else {
System.out.println("Integer list is NOT sorted");
}
}
/**
* This method generates numCount random numbers and stores them in an integer
* array. Note: For our program, numCount will always equal 1,000,000.
*
* #return nums the new integer array
*/
public static int[] generateNums(int numCount) {
// create integer array with length specified by the user
int[] nums = new int[numCount];
int max = Integer.MAX_VALUE;
for (int i = 0; i < nums.length; i++) {
nums[i] = (int) (Math.random() * max + 1);
}
// return new integer array
return nums;
}
/**
* This method implements a radix sort
*
* #param nums
* the integer array to sort
* #return nums the sorted integer array
*/
public static int[] radixSort(int[] nums) {
// find max number of digits in an element in the array
int maxDigits = findMaxDigits(nums);
// specified decimal place
int digit = 1;
// create 10 buckets
ArrayList<Integer>[] buckets = new ArrayList[10];
// iterate through the list for as many times as necessary (maxDigits)
for (int j = 0; j < maxDigits; j++) {
// initialize buckets as ArrayLists
for (int i = 0; i < buckets.length; i++) {
buckets[i] = new ArrayList<Integer>();
}
// isolate digit at specified decimal place and add the number to the
// appropriate bucket
for (int i = 0; i < nums.length; i++) {
int last = (nums[i] / digit) % 10;
buckets[last].add(nums[i]);
// convert buckets to an integer array
nums = convertToIntArray(buckets, nums);
}
// update digit to find next decimal place
digit *= 10;
}
// return sorted integer array
return nums;
}
/**
* This method converts from an ArrayList of integer arrays to an integer array
*
* #param buckets
* the ArrayList of integer arrays
* #param nums
* the integer array to return
* #return nums the new integer array
*/
public static int[] convertToIntArray(ArrayList<Integer>[] buckets, int[] nums) {
// loop through the ArrayList and put elements in order into an integer array
int i = 0;
for (ArrayList<Integer> array : buckets) {
if (array != null) {
for (Integer num : array) {
nums[i] = num;
i++;
}
}
}
// return new integer array
return nums;
}
/**
* Method to find the max number of digits in a number in an integer array
*
* #param nums
* the integer array to search through
* #return maxLength the max number of digits in a number in the integer array
*/
public static int findMaxDigits(int[] nums) {
// find maximum number
int max = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] > max) {
max = nums[i];
}
}
// find and return the number of digits in the maximum number
int maxLength = String.valueOf(max).length();
return maxLength;
}
/**
* This method is used for testing correct functionality of the above radixSort
* method.
*
* #param nums
* the integer array to check for correct sorting
* #return false if the array is sorted incorrectly, else return true.
*/
public static boolean isSorted(int[] nums) {
for (int i = 0; i < nums.length - 1; i++) {
if (nums[i] > nums[i + 1]) {
return false;
}
}
return true;
}
}

Need assistance locating the errors within the following code

The code attached below is suppose to produce this output:
The array is: 4 3 6 9 3 9 5 4 1 9
This array DOES contain 5.
Sorted by Arrays.sort(): 1 3 3 4 4 5 6 9 9 9
Sorted by Sweep Sort: 1 3 3 4 4 5 6 9 9 9
Sorted by Selection Sort: 1 3 3 4 4 5 6 9 9 9
Sorted by Insertion Sort: 1 3 3 4 4 5 6 9 9 9
But it doesn't. I followed the instruction in the book that I am reading and it didn't help. Can I get your opinion on what those errors might be? I'm not asking for solutions, I want to be pointed in the right direction as to where the errors are and what type of errors they are.
import java.util.Arrays;
/**
* This class looks like it's meant to provide a few public static methods
* for searching and sorting arrays. It also has a main method that tests
* the searching and sorting methods.
*
* TODO: The search and sort methods in this class contain bugs that can
* cause incorrect output or infinite loops. Use the Eclipse debugger to
* find the bugs and fix them
*/
public class BuggySearchAndSort {
public static void main(String[] args) {
int[] A = new int[10]; // Create an array and fill it with small random ints.
for (int i = 0; i < 10; i++)
A[i] = 1 + (int)(10 * Math.random());
int[] B = A.clone(); // Make copies of the array.
int[] C = A.clone();
int[] D = A.clone();
System.out.print("The array is:");
printArray(A);
if (contains(A,5))
System.out.println("This array DOES contain 5.");
else
System.out.println("This array DOES NOT contain 5.");
Arrays.sort(A); // Sort using Java's built-in sort method!
System.out.print("Sorted by Arrays.sort(): ");
printArray(A); // (Prints a correctly sorted array.)
bubbleSort(B);
System.out.print("Sorted by Bubble Sort: ");
printArray(B);
selectionSort(C);
System.out.print("Sorted by Selection Sort: ");
printArray(C);
insertionSort(D);
System.out.print("Sorted by Insertion Sort: ");
printArray(D);
}
/**
* Tests whether an array of ints contains a given value.
* #param array a non-null array that is to be searched
* #param val the value for which the method will search
* #return true if val is one of the items in the array, false if not
*/
public static boolean contains(int[] array, int val) {
for (int i = 0; i < array.length; i++) {
if (array[i] == val)
return true;
else
return false;
}
return false;
}
/**
* Sorts an array into non-decreasing order. This inefficient sorting
* method simply sweeps through the array, exchanging neighboring elements
* that are out of order. The number of times that it does this is equal
* to the length of the array.
*/
public static void bubbleSort(int[] array) {
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array.length-1; i++) {
if (array[j] > array[j+1]) { // swap elements j and j+1
int temp = array[j];
array[j] = array[j+1];
array[j+1] = temp;
}
}
}
}
/**
* Sorts an array into non-decreasing order. This method uses a selection
* sort algorithm, in which the largest item is found and placed at the end of
* the list, then the second-largest in the next to last place, and so on.
*/
public static void selectionSort(int[] array) {
for (int top = array.length - 1; top > 0; top--) {
int positionOfMax = 0;
for (int i = 1; i <= top; i++) {
if (array[1] > array[positionOfMax])
positionOfMax = i;
}
int temp = array[top]; // swap top item with biggest item
array[top] = array[positionOfMax];
array[positionOfMax] = temp;
}
}
/**
* Sorts an array into non-decreasing order. This method uses a standard
* insertion sort algorithm, in which each element in turn is moved downwards
* past any elements that are greater than it.
*/
public static void insertionSort(int[] array) {
for (int top = 1; top < array.length; top++) {
int temp = array[top]; // copy item that into temp variable
int pos = top - 1;
while (pos > 0 && array[pos] > temp) {
// move items that are bigger than temp up one position
array[pos+1] = array[pos];
pos--;
}
array[pos] = temp; // place temp into last vacated position
}
}
/**
* Outputs the ints in an array on one line, separated by spaces,
* with a line feed at the end.
*/
private static void printArray(int[] array) {
for (int i = 0; i < array.length; i++) {
System.out.print(" ");
System.out.print(array[i]);
}
System.out.println();
}
}
public static void bubbleSort(int[] array) {
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array.length-1; i++) { //<---- wrong increment. it should be j++
if (array[j] > array[j+1]) { // swap elements j and j+1
int temp = array[j];
array[j] = array[j+1];
array[j+1] = temp;
}
}
}
}
in this part is at least one error. You should check your loops if your programm does not determine.
I have finished my project and decided to drop a help
public static void main(String[] args) {
int[] A = new int[10]; // Create an array and fill it with small random ints.
for (int i = 0; i < 10; i++)
A[i] = 1 + (int)(10 * Math.random());
int[] B = A.clone(); // Make copies of the array.
int[] C = A.clone();
int[] D = A.clone();
System.out.print("The array is:");
printArray(A);
if (contains(A,5))
System.out.println("This array DOES contain 5.");
else
System.out.println("This array DOES NOT contain 5.");
Arrays.sort(A); // Sort using Java's built-in sort method!
System.out.print("Sorted by Arrays.sort(): ");
printArray(A); // (Prints a correctly sorted array.)
sweepSort(B);
System.out.print("Sorted by Sweep Sort: "); //Changed name
printArray(B);
selectionSort(C);
System.out.print("Sorted by Selection Sort: ");
printArray(C);
insertionSort(D);
System.out.print("Sorted by Insertion Sort: ");
printArray(D);
}
public static boolean contains(int[] array, int val) {
for (int i = 0; i < array.length; i++) {
if (array[i] == val)
return true;
//removed else
} //removed return false;
return false;
}
public static void sweepSort(int[] array) {
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array.length-1; j++) { //'i++' => 'j++'
if (array[j] > array[j+1]) { // swap elements j and j+1
int temp = array[j];
array[j] = array[j+1];
array[j+1] = temp;
}
}
}
}
public static void selectionSort(int[] array) {
for (int top = array.length - 1; top > 0; top--) {
int positionOfMax = 0;
for (int i = 1; i <= top; i++) {
if (array[i] > array[positionOfMax]) //replaced [1]
positionOfMax = i;
}
int temp = array[top]; // swap top item with biggest item
array[top] = array[positionOfMax];
array[positionOfMax] = temp;
}
}
public static void insertionSort(int[] array) {
for (int top = 1; top < array.length; top++) {
int temp = array[top]; // copy item that into temp variable
int pos = top - 1;
while (pos >= 0 && array[pos] >= temp) { // '>' => '>='
// move items that are bigger than temp up one position
array[pos+1] = array[pos];
pos--;
}
array[pos+1] = temp; // place temp into last vacated position //added '+1'
}
}
private static void printArray(int[] array) {
for (int i = 0; i < array.length; i++) {
System.out.print(" ");
System.out.print(array[i]);
}
System.out.println();
}
}
Thank for all your help guys. Using the debugger I found the for main issues
Error 1:
public static void sweepSort(int[] array) {
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array.length-1; i++) {<------// need change i++ to j++
if (array[j] > array[j+1]) { // swap elements j and j+1
int temp = array[j];
array[j] = array[j+1];
array[j+1] = temp;
}
}
}
}
Error 2 and 3:
public static void insertionSort(int[] array) {
for (int top = 1; top < array.length; top++) {
int temp = array[top]; // copy item that into temp variable
int pos = top - 1;
while (pos > 0 && array[pos] > temp) { //<----- need to change '>' to '>='
// move items that are bigger than temp up one position
array[pos+1] = array[pos];
pos--;
}
array[pos ] = temp; // place temp into last vacated position // <------------------------need to change 'array[pos ]' to 'array[pos + 1]'
}
}
Error 4:
public static boolean contains(int[] array, int val) {
for (int i = 0; i < array.length; i++) {
if (array[i] == val)
return true;
else //<---------- need to remove this
return false; //<---------- need to remove this
}
return false;
}
package sort;
import java.util.Arrays;
/**
* This class looks like it's meant to provide a few public static methods
* for searching and sorting arrays. It also has a main method that tests
* the searching and sorting methods.
*
* TODO: The search and sort methods in this class contain bugs that can
* cause incorrect output or infinite loops. Use the Eclipse debugger to
* find the bugs and fix them
*/
public class BuggySearchAndSort {
public static void main(String[] args) {
int[] A = new int[10]; // Create an array and fill it with small random ints.
for (int i = 0; i < 10; i++)
A[i] = 1 + (int)(10 * Math.random());
int[] B = A.clone(); // Make copies of the array.
int[] C = A.clone();
int[] D = A.clone();
System.out.print("The array is:");
printArray(A);
if (contains(A,5))
System.out.println("This array DOES contain 5.");
else
System.out.println("This array DOES NOT contain 5.");
Arrays.sort(A); // Sort using Java's built-in sort method!
System.out.print("Sorted by Arrays.sort(): ");
printArray(A); // (Prints a correctly sorted array.)
bubbleSort(B);
System.out.print("Sorted by Bubble Sort: ");
printArray(B);
selectionSort(C);
System.out.print("Sorted by Selection Sort: ");
printArray(C);
insertionSort(D);
System.out.print("Sorted by Insertion Sort: ");
printArray(D);
}
/**
* Tests whether an array of ints contains a given value.
* #param array a non-null array that is to be searched
* #param val the value for which the method will search
* #return true if val is one of the items in the array, false if not
*/
public static boolean contains(int[] array, int val) {
for (int i = 0; i < array.length; i++) {
if (array[i] == val)
return true;
}
return false;
}
/**
* Sorts an array into non-decreasing order. This inefficient sorting
* method simply sweeps through the array, exchanging neighboring elements
* that are out of order. The number of times that it does this is equal
* to the length of the array.
*/
public static void bubbleSort(int[] array) {
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array.length-1; j++) {
if (array[j] > array[j+1]) { // swap elements j and j+1
int temp = array[j];
array[j] = array[j+1];
array[j+1] = temp;
}
}
}
}
/**
* Sorts an array into non-decreasing order. This method uses a selection
* sort algorithm, in which the largest item is found and placed at the end of
* the list, then the second-largest in the next to last place, and so on.
*/
public static void selectionSort(int[] array) {
for (int top = array.length - 1; top > 0; top--) {
int positionOfMax = 0;
for (int i = 0; i <= top; i++) {
if (array[i] > array[positionOfMax])
positionOfMax = i;
}
int temp = array[top]; // swap top item with biggest item
array[top] = array[positionOfMax];
array[positionOfMax] = temp;
}
}
/**
* Sorts an array into non-decreasing order. This method uses a standard
* insertion sort algorithm, in which each element in turn is moved downwards
* past any elements that are greater than it.
*/
public static void insertionSort(int[] array) {
for (int top = 1; top < array.length; top++) {
int temp = array[top]; // copy item that into temp variable
int pos = top ;
while (pos > 0 && array[pos-1] >= temp) {
// move items that are bigger than temp up one position
array[pos] = array[pos-1];
pos--;
}
array[pos] = temp; // place temp into last vacated position
}
}
/**
* Outputs the ints in an array on one line, separated by spaces,
* with a line feed at the end.
*/
private static void printArray(int[] array) {
for (int i = 0; i < array.length; i++) {
System.out.print(" ");
System.out.print(array[i]);
}
System.out.println();
}
}

Sorting a String Array alphabetically by Selection Sort?

Im working on a program that alphabetically sorts a string array using compareTo method and selection sort.
Im having an issue within my minimumPosition method below. The method is designed to take the smallest element in a tail region of the array so that the selection sort program can conveniently sort the list.
My issue is that when I sort the list and print it via the tester it prints it out reverse alphabetically with a decrepency in-front. e.g. (c ,z,x,y...,b,a) opposed to (a,b,c.. y,x,z)
/**
SelectionSorter class sorts an array of Strings alphabetically.
It uses the selection sort algorithm.
*/
public class SelectionSorter
{
private String[] a;
/**
Constructs the selection sorter
#param anArray the array to sort
*/
public SelectionSorter4 (String[] anArray)
{
a = anArray;
}
/**
Sorts the array managed by this selection sorter
*/
public void sort ()
{
for (int i = 0 ; i < a.length - 1 ; i++)
{
int minPos = minimumPosition (i);
swap (minPos, i);
}
}
/**
Finds the smallest element in a tail region of the array.
The elements are String objects in this case, and the
comparison is based on the compareTo method of String.
#param from the first position of the tail region
#return the position of the smallest element in tail region
*/
private int minimumPosition (int from)
{
String holder = a [from];
int position = from;
for (int i = from ; i < a.length ; i++)
{
if (a [i].compareTo (holder) > 0)
{
holder = a [i];
position = i;
}
}
return position;
}
/**
Swaps two entries of the array
#param i the first position to swap
#param j the second position to swap
*/
private void swap (int i, int j)
{
String temp = a [i];
a [i] = a [j];
a [j] = temp;
}
}
Tester class: Relevant but there are no issues here.
/**
Tests the SelectionSorter4 class which sorts an array of Strings
alphabetically.
*/
import java.util.* ;
public class SelectionSorterTester
{
public static void main(String[] args)
{
String[] a = randomStringArray(40, 6) ;
SelectionSorter sorter = new SelectionSorter(a) ;
System.out.println(toString(a)) ;
sorter.sort() ;
System.out.println("----------Sorted:") ;
System.out.println(toString(a)) ;
System.out.println("--------------------------------") ;
}
/**
Returns a string representation of the array of Strings
#param array the array to make a string from
#return a string like [a1, a2, ..., a_n]
*/
public static String toString(String[] array)
{
String result = "[" ;
for (int i = 0 ; i < array.length - 1; i++) {
result += array[i] + ", " ;
}
result += array[array.length - 1] + "]" ;
return result ;
}
/**
Creates an array filled with random Strings.
#param length the length of the array
#param n the number of possible letters in a string
#return an array filled with length random values
*/
public static String[] randomStringArray(int length, int n)
{
final int LETTERS = 26 ;
String[] a = new String[length] ;
Random random = new Random(53) ;
for (int i = 0 ; i < length ; i++) {
String temp = "" ;
int wordLength = 1 + random.nextInt(n) ;
for (int j = 0 ; j < wordLength ; j++) {
char ch = (char)('a' + random.nextInt(LETTERS)) ;
temp += ch ;
}
a[i] = temp ;
}
return a ;
}
}
I think the issue lies within the minimumPosition method but it looks correct to me.
If you want ascendant order,
Change
if (a [i].compareTo (holder) > 0)
to
if (a [i].compareTo (holder) < 0)
Compares this object with the specified object for order. Returns a
negative integer, zero, or a positive integer as this object is less
than, equal to, or greater than the specified object.
Read more: Comparable#compareTo(..)

Sort Comparisons Counter

I have this code that sorts an array that is filled with random numbers and counts the number comparisons that it takes to complete the sort. I'm using the sort methods selection bubble and merge sort. I have the counter for the selection and the bubble but not the merge I have no clue where to put it. It might be a simple answer but I just can't get it to work.
Code:
/***********************************************************************
*
* Selection Sort:
* Reads in the array and then searches for the largest number.
* After it finds the largest number, it then swaps that number with the
* last number of the array
* Precondition: takes in an array of "n" items, which in this particular
* case is 2000, 4000, 6000, 8000, and 10000 random items in an array
* Postcondition: all numbers are sorted in ascending order
*
**********************************************************************/
public static int SelectionSort (int[] intArray) {
//Set initial count of comparisons at 0
comparisons= 0; //Number of swaps made
for(int last = intArray.length - 1; last > 0; last--) {
int largestIndex = last; //Int which places the largest number at the end of the array
// Find largest number
for(int i = 0; i < last; i++) {
//if i > the last number
if (intArray[i] > intArray[largestIndex]){
largestIndex = i; //switch the last number and i
} // end if
//Comparison+1
comparisons++;
} // end for
// Swap last element with largest element
int largest = intArray[last];
intArray[last] = intArray[largestIndex];
intArray[largestIndex] = largest;
}
//Return comparison counter
return comparisons;
}
/***********************************************************************
*
* Bubble Sort:
* Takes an array of random integers and sorts them by comparing adjacent
* numbers to one another. Whichever the larger adjacent number, Bubble
* Sort switches it towards the back end of the adjacent numbers. It does
* this until the list is fully sorted.
* Precondition: takes in a random array of integers
* Postcondition: array is sorted from smallest to largest
*
**********************************************************************/
public static int BubbleSort (int[] intArray) {
//Instance Variables
int n = intArray.length;
//boolean swap;
comparisons = 0;
//swap = false;
//for i starts at 0, when i is less than array length, i++ until reach array length
for(int i=0; i < n; i++) {
for(int j=1; j < (n-i); j++) {
if(intArray[j-1] > intArray[j]) {
//Swap the elements
int temp = intArray[j];
intArray[j] = intArray[j+1];
intArray[j+1] = temp;
//swap = true;
}
//comparisons get +1 until the for loop is done sorting
comparisons++;
} //End for loop
}
//Return the comparison counter
return comparisons;
}
/************************************************************************************
*
* Merge Sort:
* This method takes a random array and splits it in half. Once the array is
* split in half, it creates a temp0rary array. This temporary array is built by
* the method searching the two halves of the original array and puts the information
* in order stored in the temporary array. Once all the numbers are in order, the
* temporary array is then copied back to the original array.
* Precondition: take in an array of random integers
* Postcondition: return the random array sorted in ascending order
*
**********************************************************************************/
public static int mergeSort(int[] intArray) {
if(intArray.length >= 2) {
int mid = intArray.length / 2;
//Create 2 arrays to store half of the data in each
int[] first = new int[mid]; //holds first half of array
int[] second = new int[intArray.length - mid]; //holds second half of array
for(int i = 0; i < first.length; i++) {
first[i] = intArray[i];
}
for(int i = 0; i < second.length; i++) {
second[i] = intArray[mid+i];
}
mergeSort(first);
mergeSort(second);
merge(first, second, intArray); //Merge all together
}
return comparisons;
}
//merging first and second halves of mergeSort array
public static int merge(int[] first, int[] second, int[] intArray) {
int iFirst = 0;
int iSecond = 0;
int i = 0;
//moving the smaller element into intArray
while(iFirst < first.length && iSecond < second.length) {
comparisons++;
if(first[iFirst] < second[iSecond]) {
intArray[i] = first[iFirst];
iFirst++;
}
else {
intArray[i] = second[iSecond];
iSecond++;
}
i++;
}
//copying the remaining of first array
while(iFirst < first.length) {
intArray[i] = first[iFirst];
iFirst++; i++;
}
//copying the remaining of second array
while(iSecond < second.length)
{
intArray[i] = second[iSecond];
iSecond++; i++;
}
return comparisons;
}
/**************************************************************************************
* Instance methods:
* These methods perform actions to the array.
*
* copyArray()--makes a copy of the array to be used in the main class
* so that each method is able to create the same array
*
* printArray()--prints out the array for display
*
* randomArray()--creates a random integer array used by all three sorting methods
*
**************************************************************************************/
public static int[] copyArray(int[] intArray) {
//Constructor that creates copyArray
int[] copyArray = new int[intArray.length]; //siz equal to the length of the array
for(int i = 0; i < intArray.length; i++){
copyArray[i] = intArray[i];
} // end for
return copyArray;
} // end copyArray
//Prints out array
public static void printArray(int[] intArray){
//Preconditions
// Input: unsorted integer array
// Assumptions: array is full
//Postconditions
// Output: none
// Actions: array is displayed on screen
System.out.print("Array==> ");
for(int i = 0; i < intArray.length; i++){
System.out.print(intArray[i] + " ");
} // end for
System.out.println(" ");
} // end printArray
//Creates a random array that is used for each sorting method
public static int[] randomArray(int array, double range){
//Preconditions
// Input: size of array(n), range of integers (0 to range)
// Assumptions: none
//Postconditions
// Output: array of random integers 0 to floor(range)
// Actions: none
int[] intArray = new int[array];
for(int i = 0; i < array; i++){
intArray[i] = (int)(Math.random() * range);
} // end for
return intArray;
} // end randomIntArray
}
When (or just prior to) the following lines are executed:
if (intArray[i] > intArray[largestIndex]){
if(intArray[j-1] > intArray[j]) {
if(first[iFirst] < second[iSecond]) {
Your mergeSort method uses recursion. As such, it needs to take a comparisons parameter, and pass that down to each subsequent method call and receive the resulting value back again.
public static int mergeSort(int[] intArray, int comparisons) {
if(intArray.length >= 2) {
int mid = intArray.length / 2;
//Create 2 arrays to store half of the data in each
int[] first = new int[mid]; //holds first half of array
int[] second = new int[intArray.length - mid]; //holds second half of array
for(int i = 0; i < first.length; i++) {
first[i] = intArray[i];
}
for(int i = 0; i < second.length; i++) {
second[i] = intArray[mid+i];
}
comparisons = mergeSort(first, comparisons);
comparisons = mergeSort(second, comparisons);
comparisons = merge(first, second, intArray, comparisons); //Merge all together
}
return comparisons;
}
//merging first and second halves of mergeSort array
public static int merge(int[] first, int[] second, int[] intArray, int comparisons) {
int iFirst = 0;
int iSecond = 0;
int i = 0;
//moving the smaller element into intArray
while(iFirst < first.length && iSecond < second.length) {
comparisons++;
if(first[iFirst] < second[iSecond]) {
intArray[i] = first[iFirst];
iFirst++;
}
else {
intArray[i] = second[iSecond];
iSecond++;
}
i++;
}
//copying the remaining of first array
while(iFirst < first.length) {
intArray[i] = first[iFirst];
iFirst++; i++;
}
//copying the remaining of second array
while(iSecond < second.length)
{
intArray[i] = second[iSecond];
iSecond++; i++;
}
return comparisons;
}

Categories