Sort Comparisons Counter - java

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;
}

Related

Make Bubble Sorting more Efficient

I have the code for bubble sorting down below. I was wondering how I would be able to run more efficient and loop less amount of times
package bubbleSort;
public class BubbleSort {
public static void main(String[] args) {
// initialize array to sort
int size = 10;
int[] numbers = new int[size];
// fill array with random numbers
randomArray(numbers);
// output original array
System.out.println("The unsorted array: ");
printArray(numbers);
// call the bubble sort method
bubbleSort(numbers);
// output sorted array
System.out.println("The sorted array: ");
printArray(numbers);
}
public static void bubbleSort(int tempArray[]) {
//bubble sort code goes here (you code it)
// loop to control number of passes
for (int pass = 1; pass < tempArray.length; pass++) {
System.out.println(pass);
// loop to control number of comparisions for length of array - 1
for (int element = 0; element < tempArray.length - 1; element++) {
// compare side-by-side elements and swap tehm if
// first element is greater than second elemetn swap them
if (tempArray [element] > tempArray [element + 1]) {
swap (tempArray, element, element + 1);
}
}
}
}
public static void swap(int[] tempArray2,int first, int second) {
//swap code goes here (you code it)
int hold; // temporary holding area for swap
hold = tempArray2 [first];
tempArray2 [first] = tempArray2 [second];
tempArray2 [second] = hold;
}
public static void randomArray(int tempArray[]) {
int count = tempArray.length;
for (int i = 0; i < count; i++) {
tempArray[i] = (int) (Math.random() * 100) + 1;
}
}
public static void printArray(int tempArray[]) {
int count = tempArray.length;
for (int i = 0; i < count; i++) {
System.out.print(tempArray[i] + " ");
}
System.out.println("");
}
}
Any help would be greatly appreciated. I am new to coding and have been very stumped on how to improve efficiency and have it loop less times.
Bubble sort is an inefficiency sorting algorithm and there are much better sorting algorithm.
You can make a bubble sort more efficient, its called Optimized Bubble Sort (It is still quite inefficient)
Optimized bubble sort in short is, - you pass n times , but on the every iteration you 'bubble' the biggest (or smallest) element to the end of the array. Now that last item is sorted, so you don't have to compare it again.
I wrote this code last year, not to sure if it still works:
public static void bubbleSort_withFlag(Integer[] intArr) {
int lastComparison = intArr.length - 1;
for (int i = 1; i < intArr.length; i++) {
boolean isSorted = true;
int currentSwap = -1;
for (int j = 0; j < lastComparison; j++) {
if (intArr[j] < intArr[j + 1]) {
int tmp = intArr[j];
intArr[j] = intArr[j + 1];
intArr[j + 1] = tmp;
isSorted = false;
currentSwap = j;
}
}
if (isSorted) return;
lastComparison = currentSwap;
}
}
Here you can read on optimized bubble sort
Here you can find a list of different sorting algorithms that could be more efficient depending on your scenario.

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();
}
}

How to copy random generated numbers to the selection sort method. (JAVA)

import java.util.ArrayList;
import java.util.Random;
public class Sorting
{
public static int numOfComps = 0,
numOfSwaps = 0;
public static void main(String[] args)
{
System.out.println("\nOriginal order:");
int size = 5;
ArrayList<Integer> list = new ArrayList<Integer>(size);
for(int i = 1; i <= size; i++)
{
list.add(i);
}
Random rand = new Random();
while(list.size() > 0)
{
int index = rand.nextInt(list.size());
System.out.print(list.remove(index) + " ");
}
System.out.println();
int[] test = convertIntegers(list);
int[] a = new int[5];
// Selection Sort
System.out.println("\n\nSelection Sort");
// Display copy of random generated number original order
System.out.println("\nOriginal order:");
System.arraycopy(test, 0, a, 0, test.length);
System.out.println(a + " ");
// Selection Sort method
selectionSort(a);
System.out.println("\nSorted order: ");
for(int element : a)
System.out.print(element + " ");
}
public static int[] convertIntegers(ArrayList<Integer> integers)
{
int[] num = new int[integers.size()];
for (int i=0; i < num.length; i++)
{
num[i] = integers.get(i).intValue();
}
return num;
}
public static void selectionSort(int[] array)
{
int startScan; // Starting position of the scan
int index; // To hold a subscript value
int minIndex; // Element with smallest value in the scan
int minValue; // The smallest value found in the scan
// The outer loop iterates once for each element in the
// array. The startScan variable marks the position where
// the scan should begin.
for (startScan = 0; startScan < (array.length-1); startScan++)
{
// Assume the first element in the scannable area
// is the smallest value.
minIndex = startScan;
minValue = array[startScan];
// Scan the array, starting at the 2nd element in
// the scannable area. We are looking for the smallest
// value in the scannable area.
for(index = startScan + 1; index < array.length; index++)
{
if (array[index] < minValue)
{
minValue = array[index];
minIndex = index;
}
// Counts the number of values comparisons
numOfComps ++;
}
// Counts the number of values swaps
if(minIndex != startScan)
{
numOfSwaps ++;
}
// Swap the element with the smallest value
// with the first element in the scannable area.
array[minIndex] = array[startScan];
array[startScan] = minValue;
}
System.out.println("\nNumber of comps = " + numOfComps);
System.out.println("Number of swaps = " + numOfSwaps);
}
}
How do I write code to copy random generated numbers to the selection sort method so that the random generated numbers can be displayed as an exact copy under the displayed heading "Selection Sort" as well as displaying the number of comparisons and swaps, and the sorted order? The code I have provided is not working properly. Thank you for any help.
for(int i = 0; i< arr.length; i++){
//generate random number here and assign to arr[i]
}
enter code here
now add another for loop to display everything inside the array, then if you want to see if it works sort it then use another loop.

"ArrayIndexOutOfBoundsException" error when trying to add two int arrays

I'm trying to make an implementation of 'adding' the elements of two arrays in Java.
I have two arrays which contain integers and i wanna add them. I dont want to use immutable variables. I prefer do sth like that : a.plus(b);
The problem is when i add 2 arrays with different length.It tries to add the elements of b to a, but if b has a bigger length it flags an error "ArrayIndexOutOfBoundsException".
I can understand why that's happening. But how can i solve this?
How can i expand array a? :/
public void plus(int[] b)
{
int maxlength = Math.max( this.length, b.length );
if (maxlength==a.length)
{
for (int i = 0; i <= maxlength; i++)
{
a[i] = a[i] + b[i]; //ArrayIndexOutOfBoundsException error
}
}
}
i <= maxlength replace this with i < maxlength.
Your array index is starting at zero, not at one.
So the length of the array is one less than the end index of the array.
When you use <= you are trying to go one element after the last element in your array, Hence the exception.
Also you got to check the length of array b. If length of array b is smaller than a, you will end up facing the same exception.
int maxlength = Math.min( this.length, b.length ); is more appropriate.
Or incase if you don't want to miss out any elements in either of the arrays while adding, ArrayList is the answer for you. ArrayList is the self expanding array you are looking for.
Here is how you can do that -
// First ArrayList
ArrayList<Integer> a = new ArrayList<Integer>();
a.add(1);
a.add(2);
a.add(3);
// Second ArrayList
ArrayList<Integer> b = new ArrayList<Integer>();
b.add(1);
b.add(2);
b.add(3);
b.add(4);
int maxlength = Math.max(a.size(), b.size());
// Add the elements and put them in the first ArrayList in the corresponding
// position
for (int i = 0; i < maxlength; i++) {
if (i < a.size()) {
if (i < b.size()) {
int j = a.get(i);
a.set(i, j + b.get(i));
}
} else {
a.add(i, b.get(i));
}
}
for (int j : a) {
System.out.println(j);
}
How can i expand array a?
Don't use arrays if you need variable-size data structures. Use Lists.
How about this:
private int[] a;
/**
* Adds the specified array to our array, element by element, i.e.
* for index i, a[i] = a[i] + b[i]. If the incoming array is
* longer, we pad our array with 0's to match the length of b[].
* If our array is longer, then only the first [b.length] values
* of our array have b[] values added to them (which is the same
* as if b[] were padded with 0's to match the length of a[].
*
* #param b the array to add, may not be null
*/
public void plus(final int[] b)
{
assert b != null;
if (a.length < b.length) {
// Expand a to match b
// Have to move a to a larger array, no way to increase its
// length "dynamically", i.e. in place.
final int[] newA = new int[b.length];
System.arraycopy(a, 0, newA, 0, a.length);
// remaining new elements of newA default to 0
a = newA;
}
for (int i = 0; i < b.length; i++)
{
a[i] = a[i] + b[i];
}
}
Another version:
private ArrayList<Integer> aList;
public void plusList(final int[] b)
{
assert b != null;
if (aList.size() < b.length) {
aList.ensureCapacity(b.length);
}
for (int i = 0; i < b.length; i++)
{
if (i < aList.size()) {
aList.set(i, aList.get(i) + b[i]);
} else {
aList.add(b[i]);
}
}
}
Edit: Here's the full class with sample run from data in comments
public class AddableArray {
private int[] a;
public AddableArray(final int... a) {
this.a = a;
}
/**
* Adds the specified array to our array, element by element, i.e.
* for index i, a[i] = a[i] + b[i]. If the incoming array is
* longer, we pad our array with 0's to match the length of b[].
* If our array is longer, then only the first [b.length] values
* of our array have b[] values added to them (which is the same
* as if b[] were padded with 0's to match the length of a[].
*
* #param b the array to add, may not be null
*/
public void plus(final int[] b)
{
assert b != null;
if (a.length < b.length) {
// Expand a to match b
// Have to move a to a larger array, no way to increase its
// length "dynamically", i.e. in place.
final int[] newA = new int[b.length];
System.arraycopy(a, 0, newA, 0, a.length);
// remaining new elements of newA default to 0
a = newA;
}
for (int i = 0; i < b.length; i++)
{
a[i] = a[i] + b[i];
}
}
int[] get() {
return a;
}
#Override
public String toString() {
final StringBuilder sb = new StringBuilder("a[] = [ ");
for (int i = 0; i < a.length; i++) {
if (i > 0) sb.append(", ");
sb.append(a[i]);
}
sb.append(" ]");
return sb.toString();
}
public static void main (final String[] args) {
final AddableArray myAddableArray = new AddableArray(1,2,3);
System.out.println("Elements before plus(): ");
System.out.println(myAddableArray.toString());
final int b[]={1,2,3,4};
myAddableArray.plus(b);
System.out.println("Elements after plus(): ");
System.out.println(myAddableArray.toString());
}
}
Sample run:
Elements before plus():
a[] = [ 1, 2, 3 ]
Elements after plus():
a[] = [ 2, 4, 6, 4 ]
maxlength is the max between the size of a[] and b[], so in a loop from 0 to maxlength, you will get an ArrayIndexOutOfBoundsException when i exceeds the min of the size of a[] and b[].
Try this:
public void plus(int[] b)
{
Polynomial a = this;
int[] c;
int maxlength;
if (a.length>b.length) {
c=a;
maxlength=a.length;
} else {
c=b;
maxlength=b.length;
}
int ca, cb;
for (int i = 0; i < maxlength; i++)
{
if (i<this.length)
ca=a[i];
else
ca=0;
if (i<b.length)
cb=b[i];
else
cb=0;
c[i] = ca + cb;
}
}
Try replacing:
for (int i = 0; i <= maxlength; i++)
with:
for (int i = 0; i < maxlength; i++)

Categories