BubbleSort and Selection Sort - java

So I'm trying to create Bubble and Selection sort and this is the code I have so far.
package club.westcs.javabasics;
import java.util.ArrayList;
import java.util.Collections;
public class SortsRunner {
public static void BubbleSort(ArrayList<Integer> nums) {
int n = nums.size();
for (int i = 0; i < n; i++) {
boolean swapped = false;
for (int j = 0; j < n-1; j++) {
if (nums.get(j) > nums.get(j + 1)) {
int temp = nums.get(j);
nums.set(j, nums.get(j + 1));
nums.set(j + 1, temp);
swapped = true;
}
}
if (!swapped) {
break;
}
}
}
public static void SelectionSort(ArrayList<Integer> nums) {
int n = nums.size();
for (int i = 0; i < n-1; i++)
{
int min_idx = i;
for (int j = i+1; j < n; j++)
if (nums.get(j) < nums.get(min_idx))
min_idx = j;
int temp = nums.get(min_idx);
nums.set(j, nums.get(j+1)) = nums.set(i);
nums.set(i, min_idx) = temp;
}
}
public static void printArrayList(ArrayList<Integer> nums) {
for(int i = 0; i < nums.size(); i++) {
System.out.println(nums.get(i) + " ");
}
System.out.println();
}
public static ArrayList<Integer> makeRandomArrayList() {
ArrayList<Integer> nums = new ArrayList<>();
for(int i = 0; i < (int)(Math.random() * 11) + 5; i++) {
nums.add((int)(Math.random() * 100));
}
return nums;
}
public static void main(String[] args) {
printArrayList(makeRandomArrayList());
}
}
My selection sort is erroring for nums.set(j, nums.get(j+1)) = nums.set(i); and nums.set(i, min_idx) = temp; I want this portion of the code to swap the minimum element with the first element. I'm not sure how to do it correctly with the ArrayList stuff. Could someone give me some tips?

You are getting a compilation error because it is impossible to use '=' operator for void functions (such as nums.set(j, nums.get(j+1))). Setters are always void and you cannot assign smth to nothing!
The signature of ArrayList setter looks like:
public E set(int index, E element)
where first parameter is index of the array (0, 2, 3 ... N), second is a value you want to set under this index.
By the way your selection sort looks strange.
Try this code:
public static void doSelectionSort(ArrayList<Integer> arr) {
for (int i = 0; i < arr.size(); i++) {
// find position of smallest num between (i + 1)th element and last element
int pos = i;
for (int j = i; j < arr.size(); j++) {
if (arr.get(j) < arr.get(pos))
pos = j;
}
// Swap min (smallest num) to current position on array
int min = arr.get(pos);
arr.set(pos, arr.get(i));
arr.set(i, min);
printOut(i + 1, arr);
}
}

Related

Difficulty trying to sort 10 numbers inputted by a user. Must use arrays and a separate method for sorting

My program isn't sorting the numbers at all. It displays them in the order they were initially entered. It must sort them from smallest to largest number. The code below should find the largest number in the array and swap it with the last .the code is below:
import java.util.Scanner;
public class maxSorttt {
public static void main(String[] args) {
double[] ten = new double[10];
Scanner input = new Scanner(System.in);
System.out.print("Enter 10 numbers: ");
for (int i = 0; i < ten.length; i++)
ten[i] = input.nextDouble();
sort(ten);
}
public static void sort(double[] array) {
for (int i = array.length - 1; i < 0; i--) {
double currentMax = array[i];
int currentMaxIndex = i;
for (int x = i - 1; x < -1; x--) {
if (currentMax < array[x]) {
currentMax = array[x];
currentMaxIndex = x;
}
}
if (currentMaxIndex != i) {
array[currentMaxIndex] = array[i];
array[i] = currentMax;
}
}
for (int i = 0; i < array.length; i++)
System.out.print(array[i] + " ");
}
}
I believe your problem is here:
for(int i=array.length-1; i<0; i--)
array.length is not less than 0 so the for loop never runs. You probably wanted
for(int i=array.length-1; i>=0; i--)
Be Simple!
public static void selectionSort(double[] arr) {
for (int i = 0; i + 1 < arr.length; i++) {
int minIndex = findMinIndex(arr, i + 1);
if (Double.compare(arr[i], arr[minIndex]) > 0)
swap(arr, i, minIndex);
}
}
private static int findMinIndex(double[] arr, int i) {
int minIndex = i;
for (; i < arr.length; i++)
if (Double.compare(arr[i], arr[minIndex]) < 0)
minIndex = i;
return minIndex;
}
private static void swap(double[] arr, int i, int j) {
double tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}

How can I check if every single int in a randomly generated array is even and make it create another random array if it's not?

So I'm trying to create a program that creates a randomly generated array with numbers between 0 and 10.
Every time a number inside the 4x4 array is odd I want it to generate a brand new array and print every array discarded aswell until it creates a 4x4 array with only even numbers.
The problem right now is that I can't understand how to fix the last for and make it work properly with the boolean b that is supposed to restart the creation of the array.
import java.util.Scanner;
public class EvenArrayGenerator {
public static void main(String a[]) {
Boolean b;
do {
b = true;
int[][] Array = new int[4][4];
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++)
Array[i][j] = (int) (Math.random() * 11);
}
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
System.out.print(Array[i][j] + " ");
}
System.out.println();
}
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
if (Array[i][j] % 2 != 0)
b = false;
}
}
} while (b);
}
}
public class ArrayGen {
private int[][] array = new int[4][4];
private int iterations = 1; // you always start with one iteration
public static void main (String[] args) {
ArrayGen ag = new ArrayGen();
ag.reScramble();
while(!ag.isAllEven()) {
ag.reScramble();
ag.iterations++;
}
// this is just a nice visualisation
for (int i = 0; i < 4; i++) {
System.out.print("[");
for (int j = 0; j < 4; j++) {
System.out.print(ag.array[i][j] +((j != 3)? ", " : ""));
}
System.out.print("]\n");
}
System.out.println(ag.iterations + " iterations needed to get all-even array.");
}
private void reScramble () {
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
array[i][j] = (int)(Math.random() * 11);
}
}
}
private boolean isAllEven () {
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
if (array[i][j] % 2 == 1) {
return false;
}
}
}
return true;
}
}
I think this is a good solution. Refactoring your code into structured methods is never a bad idea. I hope this helps!
You are looping until you get an array that's all even. You should initialize b to be false, and update it to true in the (nested) for loop. Note that once's you've set it to false, there's no reason checking the other members of the array, and you can break out of the for loop.
Note, also, that using stream could make this check a tad more elegant:
b = Arrays.stream(arr).flatMapToInt(Arrays::stream).anyMatch(x -> x % 2 != 0)
What about generating random numbers up to 5 and double it? Then you don't have two check if they are even.
Instead of your last for loop:
for(int i=0;i<4;i++){
for(int j=0;j<4;j++){
if(Array[i][j] % 2!=0){
b=false;
break;
}
}
if(!b){
break;
}
}
if(!b){
break;
}
Alternatively, you could do an oddity check when you are generating the elements. Something like:
int element;
for(int i=0;i<4;i++){
for(int j=0;j<4;j++){
do{
element = (int)(Math.random()*11);
}while(element % 2 !=0)
Array[i][j] = element;
}
}
That way you don't have to check the values, they will always be even.
This should work:
import java.util.Scanner;
public class EvenArrayGenerator{
public static void main(String a[]){
boolean anyOdd;
int array = 0;
do{
System.out.println ("Array " + ++array + ":");
anyOdd=false;
int[][] Array = new int[4][4];
for(int i=0;i<4;i++) {
for(int j=0;j<4;j++) {
Array[i][j] = (int)(Math.random()*11);
}
}
for(int i=0;i<4;i++){
for(int j=0;j<4;j++){
System.out.print(Array[i][j] + " ");
}
System.out.println();
}
for(int i=0;i<4;i++){
for(int j=0;j<4;j++){
anyOdd |= Array[i][j] % 2!=0;
}
}
} while(anyOdd);
}
}
As you can see, I just modified the condition from b to anyOdd, so if there is any odd number, it will iterate again.
Also, you can check it when you generate the random numbers, so you avoid a second loop:
import java.util.Scanner;
public class EvenArrayGenerator{
public static void main(String a[]){
boolean anyOdd;
int array = 0;
do{
System.out.println ("Array " + ++array + ":");
anyOdd=false;
int[][] Array = new int[4][4];
for(int i=0;i<4;i++) {
for(int j=0;j<4;j++) {
Array[i][j] = (int)(Math.random()*11);
anyOdd |= array[i][j] % 2 != 0;
}
}
for(int i=0;i<4;i++){
for(int j=0;j<4;j++){
System.out.print(Array[i][j] + " ");
}
System.out.println();
}
} while(anyOdd);
}
}
public class EvenArrayGenerator {
public static void main(String a[]) {
int[][] arr = createAllEvenArray(4);
printArray(arr);
}
private static int[][] createAllEvenArray(int size) {
while (true) {
int[][] arr = createArray(size);
printArray(arr);
if (isAllEven(arr))
return arr;
}
}
private static int[][] createArray(int size) {
int[][] arr = new int[size][size];
for (int i = 0; i < arr.length; i++)
for (int j = 0; j < arr.length; j++)
arr[i][j] = (int)(Math.random() * 11);
return arr;
}
private static void printArray(int[][] arr) {
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
if (j > 0)
System.out.print("\t");
System.out.format("%2d", arr[i][j]);
}
System.out.println();
}
System.out.println();
}
private static boolean isAllEven(int[][] arr) {
for (int i = 0; i < arr.length; i++)
for (int j = 0; j < arr.length; j++)
if (arr[i][j] % 2 != 0)
return false;
return true;
}
}

Error in Java Insertion Sort

I've attempted to code an Insertion Sort in java via pseudo code from a book. The output for this code should be numbers in ascending order but for some reason I get 10,4,5,6,7,8,9. Any help is greatly appreciated! Thanks!
public class InsertionSort {
public int Array[] = {10,9,8,7,6,5,4};
public static void main(String[] args) {
InsertionSort obj1 = new InsertionSort();
}
public InsertionSort() {
InsertionSortMethod();
PrintArray();
}
public void InsertionSortMethod() {
for(int j = 2; j < Array.length; j++) {
int key = Array[j];
int i = j - 1;
while(i > 0 && Array[i] > key) {
Array[i + 1] = Array[i];
i = i - 1;
}
Array[i + 1] = key;
}
}
public void PrintArray() {
for(int i = 0; i < Array.length; i++) {
System.out.println(Array[i]);
}
}
}
Start the for loop from j=1 like this :
for(int j = 1; j < array.length; j++) {
and modify while loop condition like this:
while(i >= 0 && array[i] > key) {
Correct working code :
public class InsertionSort {
public int array[] = {10,9,8,7,6,5,4};
public static void main(String[] args) {
InsertionSort obj = new InsertionSort();
obj.insertionSortMethod();
obj.printArray();
}
public void insertionSortMethod() {
for(int j = 1; j < array.length; j++) {
int key = array[j];
int i = j - 1;
while(i >= 0 && array[i] > key) {
array[i + 1] = array[i];
i = i - 1;
}
array[i + 1] = key;
}
}
public void printArray() {
for(int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
}
}
At the third line of your code i.e.,
InsertionSort obj1 = new InsertionSort();
You are making an object of InsertionSort class but in your code, it is defined as a function I think it is a constructor you must mention the class for more convenience of the reader.
Apart from that, you are starting your loop with 2 for(int j = 2; j < Array.length; j++)
why so? your one element got missed so start j with 1
:)
Thanks to all the answers. I have also found by tracing the algorithm that flipping the second 'greater than' sign to a 'less than' sign on the 5th line of the algorithm does the trick for working in descending order. This may possibly be a typo in the book i'm reading. Thanks again!
try this method
public int[] insertionSort(int[] list) {
int i, j, key, temp;
for (i = 1; i < list.length; i++) {
key = list[i];
j = i - 1;
while (j >= 0 && key < list[j]) {
temp = list[j];
list[j] = list[j + 1];
list[j + 1] = temp;
j--;
}
}
return list;
}
package com.borntoinnovation.datastructure;
import java.util.Arrays;
public class SortingInsertion {
public static void main(String[] args) {
int[] array = new int[] { 4, 3, 2, 20, 12, 1, 5, 6 };
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < i; j++) {
if (array[i] < array[j]) {
int temp = array[i];
for (int k = i; k > j; k--) {
array[k] = array[k - 1];
}
array[j] = temp;
}
}
System.out.println(Arrays.toString(array));
}
}// end of main()
}

ArraySort not displaying?

It is not giving any output but the code runs without error.I wanted to show all the methods including the result for bubble sort, selection sort and compare sort? How do I call the methods. When I run it, it is not giving me any output. So, I just needed help to run the code.
public static void main(String[] args) {
int[] A = new int[100];
int[] B = new int[100];
}
//get a random number;
private int getRand() {
Random in = new Random();
return in.nextInt(100);
}
//fill an array with numbers from 0 to 99;
public static void fillArray(int[] array) {
for (int i = 0; i < array.length; i++) {
array[i] = i;
}
}
//copy an array to another;
public static void copyArray(int[] aArray, int[] bArray) {
for (int i = 0; i < aArray.length; i++) {
bArray[i] = aArray[i];
}
}
//swap two numbers in an array according to index;
private void swap(int[] array, int i, int j) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
//random select two numbers in an array and switch them;
int disorderArray(int[] array) {
int i, j;
i = getRand();
j = getRand();
swap(array, i, j);
//System.out.println("the index of the 2 swapped numbers are " + i + " " +
j
);
return i;
}
//print out the array;
public static void printArray(int[] array, int col) {
for (int i = 0; i < array.length - col + 1; i += col) {
for (int j = i; j < i + col; j++)
System.out.print("number " + j + " is " + array[j] + "; ");
System.out.println();
}
for (int i = array.length - array.length % col; i < array.length; i++)
System.out.print("number " + i + " is " + array[i] + "; ");
System.out.println();
System.out.println();
}
//bubble sort;
public void bubbleSort(int[] array) {
for (int i = array.length - 1; i > 0; i--) {
for (int j = 0; j < i; j++) {
if (array[j] > array[j + 1])
swap(array, j, j + 1);
}
}
}
//selection sort;
public void selectionSort(int[] array) {
for (int i = 0; i < array.length - 1; i++) {
int p = i;
for (int j = i + 1; j < array.length; j++)
if (array[p] > array[j])
p = j;
if (i != p)
swap(array, i, p);
}
}
//compare two arrays;
public static boolean compareArrays(int[] aArray, int[] bArray) {
boolean s = true;
int i = 0;
if (aArray.length == bArray.length) {
while (s && i < aArray.length) {
if (aArray[i] != bArray[i])
s = false;
i++;
}
}
return s;
}
}
You have implemented some methods, but you need to invoke them from your main method, e.g.
public static void main(String[] args) {
int[] A = new int[100];
int[] B = new int[100];
fillArray(A);
// more method calls...
}
Note, you have implemented both class (static) methods and instance (non-static) methods. The semantics for how you call them differs. If your program is is implemented in a class named Foo, you can write the following:
// method call to class method
Foo.fillArray();
// method call to instance metod requires an instance
Foo fooInstance = new Foo();
int randomNumber = fooInstance.getRand();
Normally, you use instance methods to manipulate instance variables and class methods to manipulate class variables or more commonly as helper methods that do not involve state at all. More information regarding this can be found in the Understanding Class Members chapter of Oracle's Java Tutorial (scroll down to Class Methods).

Sorting an array of string data using the insertion sort method

I'm having trouble using insertion to sort an array of strings.
When I compile the following code:
public class Project1 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String names[]=new String[5];
int size=names.length;
System.out.println("Enter the 5 car manufacturers: ");
//Load Array
for (int i = 0; i < 5; i++) {
names[i] = input.nextLine();
}
//Print descending order list
String[] descSort;
descSort=bubbleSortDesc(names);
System.out.println("Car manufacturers listed sorted in descending order (via BubbleSort): ");
for (int x=0; x < names.length; x++) {
System.out.println(names[x]);
}
//Print ascending order list
insertionSortAsc(names, size);
System.out.println("Car manufacturers listed sorted in ascending order (via InsertionSort): ");
for (int z=0; z < names.length; z++) {
System.out.println(names[z]);
}
}ยจ
public static String[] bubbleSortDesc(String[] names) {
String temp;
int passNum, i, result;
for (passNum=1; passNum <= 4; passNum++) {
for (i = 0; i<=(4-passNum); i++) {
result=names[i].compareToIgnoreCase(names[i+1]);
if(result<0) {
temp=names[i];
names[i]=names[i+1];
names[i+1]=temp;
}
}
}
return names;
}
public static void insertionSortAsc(String[] names, int i) {
String temp = names[i];
int j = i-1;
while (j >= 0 && names[j].compareToIgnoreCase(temp) > 0) {
names[j+1]=names[j];
j--;
}
names[j+1]=temp;
}
public static void insertionSort(String[] names, int n) {
for(int i = 1; i<n; i++) {
insertionSortAsc(names, i);
}
}
}
It gives me the error:
cannot find symbol- method insert(java.lang.String[], int)
I suspect it has something to do with the fact that we were told to use our book as reference for the code, yet the book only deals with sorting data of type int and there are no examples for sorting string data.
Any help is appreciated.
Edit: After fixing the error, the program compiles and executes but after inputting the data it crashes and gives me the following error
java.lang.ArrayIndexOutofBoundsException:
5
This error highlights the line String temp = names[i]
You haven't defined a method named insert.
This will work the way you intend:
public static void insertionSortAsc(String[] names, int n)
{
for(int i = 1; i<n; i++)
{
insert(names, i);
}
}
public static void insert(String[] names, int i)
{
String temp = names[i];
int j = i - 1;
while (j >= 0 && names[j].compareToIgnoreCase(temp) > 0)
{
names[j + 1]= names[j];
j--;
}
names[j + 1] = temp;
}
public static void insertionSort(int... arr) {
for (int i = 1; i < arr.length; i++) {
if (arr[i] >= arr[i - 1])
continue;
int j = i - 1;
for (; j >= 0; j--)
if (arr[j] < arr[i])
break;
int tmp = arr[i];
System.arraycopy(arr, j + 1, arr, j + 2, i - j - 1);
arr[j + 1] = tmp;
}
}

Categories