ArraySort not displaying? - java

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).

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

BubbleSort and Selection Sort

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

why double if statement in java return empty search in array

I wrote the code below in java to compare and return a searhKey in the array, but is not returning anything in the array
package arraytest;
public class ArrayTest {
public static void main(String[] args) {
int objType[] = new int[10];
int i = 0;
int arrSize;
int searchKey = 0;
objType[0] = 20;
objType[1] = 15;
objType[2] = 10;
objType[3] = 11;
objType[4] = 17;
arrSize = 5;
for (i = 0; i < arrSize; i++) {
System.out.println(objType[i]);
}
searchItem(objType, searchKey, arrSize);
}
public static void searchItem(int objType[], int searchKey, int arrSize) {
int i = 0, temp = 10;
for (int j = 0; j < arrSize; j++)
if (objType[i] == temp) {
searchKey = temp;
if (j == arrSize)
System.out.println("Search key not found");
System.out.println("found search key " + searchKey);
}
}
}
You're iterating on j but comparing using i:
for (int j = 0; j < arrSize; j++)
if (objType[i] == temp) {
Also you pass searchKey as parameter but use it as a temporary variable for output, which doesn't make much sense.
Make sure you do want to pass arrSize since you can use objType.length or enhanced for (it's still OK if you want to search part of the array, but the name is misleading then, but I doubt that was your intention)
That could be:
public static void searchItem(int arr[], int searchKey) {
int found = 0;
for (int item : arr) {
if (item == searchKey) {
System.out.println("found search key " + searchKey);
found ++;
}
}
if (found == 0) System.out.println("Search key not found");
}
You may want to break, however, if the key was found, or return the number of found keys. This way the method only produces output.
Your nested if statement will never get hit:
if (j == arrSize)
System.out.println("Search key not found");
This is because of your foor loop for (int j = 0; j < arrSize; j++) which means that if j == arrSize the loop will exit and nothing inside will be run. You want to put your if statement outside your for loop, and change j to i:
int i = 0, temp = 10;
for (i = 0; i < arrSize; i++) {
if (objType[i] == temp) {
searchKey = temp;
System.out.println("found search key " + searchKey);
break;
}
}
if (i == arrSize) {
System.out.println("Search key not found");
}
This might be one plausible solution (thanks to comments from #Tom, and I have tested the code):
package arraytest;
public class ArrayTest {
public static void main(String[] args) {
int objType[] = new int[10];
int i = 0;
int arrSize;
int searchKey = 10;
objType[0] = 20;
objType[1] = 15;
objType[2] = 10;
objType[3] = 11;
objType[4] = 17;
arrSize = 5;
for (i = 0; i < arrSize; i++) {
System.out.println(objType[i]);
}
searchItem(objType, searchKey, arrSize);
}
public static void searchItem(int objType[], int searchKey, int arrSize) {
for (int j = 0; j < arrSize; j++) {
if (objType[j] == searchKey) {
System.out.println("found search key " + searchKey);
return;
}
}
System.out.println("Search key not found");
}
}

null pointer exception sorting merged array list

I have been trying to figure out how to properly print the return of my method.
When the program prints the return of my method, I am giving a nullPointerException error on line 45(the line where i am trying to print the method).
*I did try to make the return to the method static so it is accessible.
How do I initialize the "answer" variable so that i can print it outside of my method?
Thank you in advance
import javax.swing.JOptionPane;
public class ListSortMerge {
static int[]answer;
public static void main(String[] args) {
int v1 = 0, v2 = 0;
for(int c = 0; c <= 1; c++) {
String values = JOptionPane.showInputDialog("How many values would you like to store in list "+(c+1)+"?");
if (c==0) {
v1 = Integer.parseInt(values);
}
else{
v2 = Integer.parseInt(values);
}
}
int[] numbers1 = new int[v1];
int[] numbers2 = new int[v2];
merge(numbers1,numbers2);
int i;
System.out.println("\nList 1 before the sort");
System.out.println("--------------------");
for(i = 0; i < (v1); i++) {
System.out.println(numbers1[i]);
}
System.out.println("\nList 2 before the sort");
System.out.println("--------------------");
for(i = 0; i < (v2); i++) {
System.out.println(numbers2[i]);
}
System.out.println("\nList after the sort");
System.out.println("--------------------");
for(i = 0; i < (v1+v2); i++) {
System.out.println(answer[i]);
}
}
public static int[] merge(int[] a, int[] b) {
int[] answer = new int[a.length + b.length];
for(int c = 0; c < (a.length); c++)
{
String aVal1 = JOptionPane.showInputDialog("Input list 1 value " +(c+1));
a[c] = Integer.parseInt(aVal1);
}
for ( int c = 0; c < (b.length); c++){
String aVal2 = JOptionPane.showInputDialog("Input list 2 value " +(c + 1));
b[c] = Integer.parseInt(aVal2);
}
int i = 0, j = 0, k = 0;
while (i < a.length && j < b.length)
{
if (a[i] < b[j])
answer[k++] = a[i++];
else
answer[k++] = b[j++];
}
while (i < a.length)
answer[k++] = a[i++];
while (j < b.length)
answer[k++] = b[j++];
return answer;
}
}
You have two different answer variables: one is a local variable in the merge function and another is a static field in the class. You never initialize the second one.

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