I have an array including user's inputs. The program is about Bubble sort, Selection sort and Insertion sort. First Bubble, Second Selection and then Insertion sort comes.
I couldn't manage to solve a problem. When the code run into selection sort, the array is already sorted by bubble sort.
I tried to make 2 temporary arrays at first to use the "source array" at selection and insertion sorting but those arrays re-arranged by bubble sort again. ( Which I don't understand why )
Is there any way to sort my array seperately or I have to make them methods ? I'm counting the swaps and comparisons also BTW. Thanks !
System.out.println("• Please enter the number of elements in the Sorting Bag:");
length = input.nextInt();
System.out.println("• The number of elements: " + length);
int[] SorBag = new int[length];
int[] SorBag2 = new int[length];
int[] SorBag3 = new int[length];
System.out.println("• Please enter the elements of Sorting Bag:");
for (int i = 0; i < SorBag.length ; i++) {
SorBag[i] = input.nextInt();
}
SorBag2 = SorBag;
SorBag3 = SorBag;
System.out.print("• Elements in the Sorting Bag are:");
for (int j = 0; j < SorBag.length; j++) {
System.out.print(" " + SorBag[j]);
}
System.out.println("");
System.out.println("");
//Bubble Sort
for (int i = 1; i < SorBag.length; i++) {
for (int j = 0; j < SorBag.length - i; j++) {
BComparison++;
if (SorBag[j] > SorBag[j + 1]) {
BSwaps++;
temp1 = SorBag[j + 1];
SorBag[j + 1] = SorBag[j];
SorBag[j] = temp1;
}
}
}
System.out.print("• Bubble Sort:");
for (int k = 0; k < SorBag.length; k++) {
System.out.print(" " + SorBag[k] + " ");
}
System.out.print("Comparisons: " + BComparison + " Swaps: " + BSwaps);
System.out.println(" ");
//Selection Sort
for (int i = 0; i < SorBag2.length; i++) {
min = i;
for (int j = i + 1; j < SorBag2.length; j++) {
SComparison++;
if (SorBag2[j] < SorBag2[min]) {
min = j;
}
if (min != i) {
temp2 = SorBag2[i];
SorBag2[i] = SorBag2[min];
SorBag2[min] = temp2;
SSwaps++;
}
}
}
System.out.print("• Selection Sort:");
for (int k = 0; k < SorBag2.length; k++) {
System.out.print(" " + SorBag2[k] + " ");
}
System.out.print("Comparisons: " + SComparison + " Swaps: " + SSwaps);
System.out.println(" ");
//Insertion Sort
for (int i = 1; i < SorBag3.length; i++) {
int j = 0;
while (j > i && SorBag3[j] < SorBag3[j - 1]) {
temp3 = SorBag3[j];
SorBag3[j] = SorBag3[j - 1];
SorBag3[j - 1] = temp3;
ISwaps++;
j--;
}
IComparison++;
}
System.out.print("• Insertion Sort:");
for (int k = 0; k < SorBag3.length; k++) {
System.out.print(" " + SorBag3[k] + " ");
}
System.out.print("Comparisons: " + IComparison + " Swaps: " + ISwaps);
System.out.println(" ");
}
}
SorBag2 = SorBag and SorBag3 = SorBag copies the reference of SorBag to the other two arrays, instead of only copying the data. So instead of:
System.out.println("• Please enter the elements of Sorting Bag:");
for (int i = 0; i < SorBag.length ; i++) {
SorBag[i] = input.nextInt();
}
SorBag2 = SorBag;
SorBag3 = SorBag;
Try this:
System.out.println("• Please enter the elements of Sorting Bag:");
for (int i = 0; i < SorBag.length ; i++) {
int nextInt = intput.nextInt();
SorBag[i] = nextInt;
SorBag2[i] = nextInt;
SorBag3[i] = nextInt;
}
Related
So, this code is supposed to do the following:
Check if the neighboring members in a row of the square matrix and write them if their sum is an even number and also write the members which sum is a odd number. But it sends an error in the first if statement. But it only does the first row and outputs the Index out of bounds. Here is the code:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Ucitati broj clanova kvadratne matrice: ");
int n = scan.nextInt();
int niz[][] = new int[n][n];
System.out.println("Ucitati clanove matrice: ");
for (int i = 0; i < niz.length; i++) {
for (int j = 0; j < niz.length; j++) {
System.out.print("n[" + i + ", " + j + "]" + "=");
niz[i][j] = scan.nextInt();
}
}
System.out.println();
for (int i = 0; i < niz.length; i++) {
for (int j = 0; j < niz.length; j++) {
System.out.print(niz[i][j] + " ");
}
System.out.println();
}
System.out.println("Susedni clanovi cija je suma parna su: ");
for (int i = 0; i < niz.length; i++) {
for (int j = 0; j < niz.length; j++) {
if ((niz[i][j] + niz[i][j + 1]) % 2 == 0) {
System.out.print(niz[i][j] + " " + niz[i][j + 1] + "; ");
}
}
}
System.out.println("Susedni clanovi cija je suma neparna su: ");
for (int i = 0; i < niz.length; i++) {
for (int j = 0; j < niz.length; j++) {
if ((niz[i][j] + niz[i][j + 1]) % 2 != 0) {
System.out.print(niz[i][j] + " " + niz[i][j + 1] + "; ");
}
}
}
}
System.out.println are in Serbian so if u need a translate let me know, but that shouldn't be needed.
As the title says, I want to know a way (in Java) to find which row (in a matrix/2D Array) and column has the highest sum of its numbers.
There might be an easy solution but I'm struggling to find it.
I currently have the first part of the program but I can't seem to find a solution to the second part, which is finding the row and column with the highest sum.
Desired output
I'm a beginner at this so any kind of advice would be appreciated.
This is the first part of my code:
import javax.swing.JOptionPane;
public class summat{
public static void main(String[] args){
int mat[][] = new int [3][3];
int num, sumop, sumw, i, j, mayop = 0, mayw = 0;
for(i=0;i<3;i++){
for(j=0;j<3;j++){
String input = JOptionPane.showInputDialog(null, "Products sold by the operator " + (i+1) + " in week " + (j+1) + ".");
mat[i][j] = Integer.parseInt(input);
}
}
/*Sum of individual rows*/
for(i=0;i<3;i++){
sumop = 0;
for(j=0;j<3;j++){
sumop = sumop + mat[i][j];
}
JOptionPane.showMessageDialog(null, "The operator " + (i+1) + " sold " + sumop + " units.");
}
/*Sum of individual columns*/
for(j=0;j<3;j++){
sumw = 0;
for(i=0;i<3;i++){
sumw = sumw + mat[i][j];
}
JOptionPane.showMessageDialog(null, "In week " + (j+1) + " the company sold " + sumw + " units.");
}
}
}
public static void method(int[] arr, int row, int col) {
// converting array to matrix
int index = 0;
int mat[][] = new int[row][col];
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
mat[i][j] = arr[index];
index++;
}
}
// calculating sum of each row and adding to arraylist
ArrayList<Integer> rsum = new ArrayList<Integer>();
for (int i = 0; i < row; i++) {
int r = 0;
for (int j = 0; j < col; j++) {
r = r + mat[i][j];
}
rsum.add(r);
}
// calculating sum of each col and adding to arraylist
ArrayList<Integer> csum = new ArrayList<Integer>();
for (int i = 0; i < row; i++) {
int sum = 0;
for (int j = 0; j < col; j++) {
sum = sum + mat[j][i];
}
csum.add(sum);
}
System.out.println(
"Maximum row sum is " + Collections.max(rsum) + " at row " + rsum.indexOf(Collections.max(rsum)));
System.out.println(
"Maximum col sum is " + Collections.max(csum) + " at col " + csum.indexOf(Collections.max(csum)));
}
public static void method(int[][] mat, int row, int col) {
// calculating sum of each row and adding to arraylist
ArrayList<Integer> rsum = new ArrayList<Integer>();
for (int i = 0; i < row; i++) {
int r = 0;
for (int j = 0; j < col; j++) {
r = r + mat[i][j];
}
rsum.add(r);
}
// calculating sum of each col and adding to arraylist
ArrayList<Integer> csum = new ArrayList<Integer>();
for (int i = 0; i < row; i++) {
int sum = 0;
for (int j = 0; j < col; j++) {
sum = sum + mat[j][i];
}
csum.add(sum);
}
System.out.println(
"Maximum row sum is " + Collections.max(rsum) + " at row " + rsum.indexOf(Collections.max(rsum)));
System.out.println(
"Maximum col sum is " + Collections.max(csum) + " at col " + csum.indexOf(Collections.max(csum)));
}
You can use the following logic and implement it as desired.
// Row calculation
int rowSum = 0, maxRowSum = Integer.MIN_VALUE, maxRowIndex = Integer.MIN_VALUE;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
rowSum = rowSum + mat[i][j];
}
if (maxRowSum < rowSum) {
maxRowSum = rowSum;
maxRowIndex = i;
}
rowSum = 0; // resetting before next iteration
}
// Column calculation
int colSum = 0, maxColSum = Integer.MIN_VALUE, maxColIndex = Integer.MIN_VALUE;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
colSum = colSum + mat[j][i];
}
if (maxColSum < colSum) {
maxColSum = colSum;
maxColIndex = i;
}
colSum = 0; // resetting before next iteration
}
System.out.println("Row " + maxRowIndex + " has highest sum = " +maxRowSum);
System.out.println("Col " + maxColIndex + " has highest sum = " +maxColSum);
Here we use two additional variables maxRowSum to store the highest sum of the row and maxRowIndex to store the index of the highest row. The same applies for column as well.
You can have to integers one for row(maxRow) and one for col(maxCol) to maintain max values:
int maxRow = Integer.MIN_VALUE;
/*Sum of individual rows*/
for(i=0;i<3;i++){
sumop = 0;
for(j=0;j<3;j++){
sumop = sumop + mat[i][j];
}
if(maxRow > sumop)
maxRow = sumop;
JOptionPane.showMessageDialog(null, "The operator " + (i+1) + " sold " + sumop + " units.");
}
int maxCol = Integer.MIN_VALUE;
/*Sum of individual columns*/
for(j=0;j<3;j++){
sumw = 0;
for(i=0;i<3;i++){
sumw = sumw + mat[i][j];
}
if(maxCol > sumw)
maxCol = sumw;
JOptionPane.showMessageDialog(null, "In week " + (j+1) + " the company sold " + sumw + " units.");
}
Here's a method that first computes both row-wise and column-wise sums in one loop (the same one it uses to find max row sum), and a second one to find the max column sum:
//This returns an array with {maxRowIndex, maxColumnIndex}
public static int[] findMax(int[][] mat) {
int[] rowSums = new int[mat.length];
int[] colSums = new int[mat[0].length];
int maxRowValue = Integer.MIN_VALUE;
int maxRowIndex = -1;
for (int i = 0; i < mat.length; i++) {
for (int j = 0; j < mat[i].length; j++) {
rowSums[i] += mat[i][j];
colSums[j] += mat[i][j];
}
if (rowSums[i] > maxRowValue) {
maxRowIndex = i;
maxRowValue = rowSums[i];
}
// display current row message
JOptionPane.showMessageDialog(null, "The operator " +
(i + 1) + " sold " + rowSums[i] + " units.");
}
int maxColumnValue = Integer.MIN_VALUE;
int maxColumnIndex = -1;
// look for max column:
for (int j = 0; j < mat[0].length; j++) {
if (colSums[j] > maxColumnValue) {
maxColumnValue = colSums[j];
maxColumnIndex = j;
}
// display column message
JOptionPane.showMessageDialog(null, "In week " +
(j + 1) + " the company sold " + colSums[j] + " units.");
}
return new int[] { maxRowIndex, maxColumnIndex };
}
The following test (I had to hard-code matrix values) produces [2, 2]:
public static void main(String[] args) {
int mat[][] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
int[] maxValues = findMax(mat);
System.out.println("Max row index: " +
maxValues[0] + ". Max Column index: " + maxValues[1]);
}
As of now I wrote the program, and it sorts the students scores from lowest to highest. I need to reverse it where it sorts from highest to lowest.
public static void sortStudentScores(String namesArry[], int scoresArry[]) {
int tempScore;
String tempName;
for (int i = 0; i < scoresArry.length; i++) {
for ( int j= i + 1; j < scoresArry.length; j++) {
if (scoresArry[i] > scoresArry[j]) {
tempScore = scoresArry[i];
scoresArry[i] = scoresArry[j];
scoresArry[j] = tempScore;
tempName = namesArry[i];
namesArry[i] = namesArry[j];
namesArry[j] = tempName;
}
}
}
System.out.println("\nAscending Order:");
for (int i = 0; i < namesArry.length; i ++) {
System.out.println("Student Name: " + namesArry[i] + " " + scoresArry[i]);
}
}
public static void sortStudentScores(String namesArry[], int scoresArry[]) {
int tempScore;
String tempName;
for (int i = 0; i < scoresArry.length; i++) {
for ( int j= i + 1; j < scoresArry.length; j++) {
if (scoresArry[i] < scoresArry[j]) {
tempScore = scoresArry[i];
scoresArry[i] = scoresArry[j];
scoresArry[j] = tempScore;
tempName = namesArry[i];
namesArry[i] = namesArry[j];
namesArry[j] = tempName;
}
}
}
System.out.println("\nDescending Order:");
for (int i = 0; i < namesArry.length; i ++) {
System.out.println("Student Name: " + namesArry[i] + " " +
scoresArry[i]);
}
}
Here just the logic for sorting has been modified, in your code you ensured that the element at smaller index has smaller score. To do it in descending order, you just need to do the opposite.
Cheers!
update your code as below:
if (scoresArry[i] < scoresArry[j])
I would suggest that you define a class Student and define your comparator for sorting (see: http://www.baeldung.com/java-sorting)
Am confused about getting the "sub diagonal" for 2D array, I can get the columns , rows and major diagonal, but i don't know how to get sub diagonal, here is what i'v done so far:
int size = input.nextInt();
int[][] list = initiateArr(size);
for (int i = 0; i < list.length; i++) {
for (int j = i ; j < i + 1; j++) {
System.out.print(list[i][j] + " ");
}
}
My attempt for "sub diagonal":
for (int i = 0; i < list.length; i++) {
for (int j = (list.length / 2) + 1; j > list.length - (i + 1) ; j--) {
System.out.print(list[i][j] + " ");
System.out.println("j = " + j);
}
}
How to get sub diagonal?
I can get the major diagonal right as described in the output 1111, the sub diagonal should be 1010.
Here is the answer. Let me know if you have any questions.
public static void main(String args[]) {
int[][] list = {{1,2,3}, {4,5,6},{7,8,9}};
int matrixSize = 3;
System.out.println("Subdiagonal");
for( int i = 0; i < matrixSize ; i ++){
System.out.print( list[i][matrixSize - i -1] + " ");
}
System.out.println("");
System.out.println("Major ");
for( int i = 0; i < matrixSize ; i ++){
System.out.print( list[i][i] + " ");
}
}
Alright, so I tried implementing the bubble sort algorithm into my code, but now my output for the second array (in my code) is giving me a ton of zeros. Can anybody tell me what is wrong with my code and how I can fix it so the zeros are removed and the only thing that remains in the output for my second array are the fixed numerically?
public static void main(String[] args) {
System.out.println("Input up to '10' numbers for current array: ");
int[] array1 = new int[10];
int i;
Scanner scan = new Scanner(System.in);
for (i = 0; i < 10; i++) {
System.out.println("Input a number for " + (i + 1) + ": ");
int input = scan.nextInt();
if (input == -9000) {
break;
} else {
array1[i] = input;
}
}
System.out.println("\n" + "Original Array: ");
for (int j = 0; j < i; j++) {
System.out.println((j + 1) + ": " + array1[j]);
}
int[] array2 = new int[i];
System.out.println("\n" + "Organized Array: ");
for (int j = 0; j < i; j++) {
int temp;
boolean organized = false;
while (organized == false) {
organized = true;
for (i = 0; i < array1.length - 1; i++) {
if (array1[i] > array1[i + 1]) {
temp = array1[i + 1];
array1[i + 1] = array1[i];
array1[i] = temp;
organized = false;
}
}
}
for (i = 0; i < array1.length; i++) {
System.out.println(array1[i]);
}
scan.close();
}
}
}
Copy your array1 to an array2 of the correct length before sorting, something like
for (i = 0; i < 10; i++) {
System.out.println("Input a number for " + (i + 1) + ": ");
int input = scan.nextInt();
if (input == -9000) {
break;
}
array1[i] = input;
}
int[] array2 = Arrays.copyOfRange(array1, 0, i);
System.out.println("Before sorting: " + Arrays.toString(array2));
Arrays.sort(array2); // <-- How I would sort.
System.out.println("After sorting: " + Arrays.toString(array2));
The reason this is necessary is because i might not be 10 in which case your array contains 0(s) to fill the other positions.
Is it possible to move all my numbers from Array 1 to Array 2 using a for-loop?
Yes. You could implement a copyOfRange function with a for loop,
private static int[] copyOfRange(int[] arr, int start, int end) {
int pos = 0;
int[] out = new int[end - start];
for (int i = start; i < end; i++) {
out[pos] = arr[i];
pos++;
}
return out;
}
the built-in version is almost certainly better.
1) You are printing the array multiple times, I think you might be giving 0 as input and thats the reason you are seeing 0's everywhere.
2) You have created array2 which is not necessary.
Move the printing logic out of for loop as in the below snippet. Otherwise your logic looks fine except fot the wrong looping of print statement.
public static void main(String args[]) {
System.out.println("Input up to '10' numbers for current array: ");
int[] array1 = new int[10];
int i;
Scanner scan = new Scanner(System.in);
for (i = 0; i < 10; i++) {
System.out.println("Input a number for " + (i + 1) + ": ");
int input = scan.nextInt();
if (input == -9000) {
break;
} else {
array1[i] = input;
}
}
System.out.println("\n" + "Original Array: ");
for (int j = 0; j < i; j++) {
System.out.println((j + 1) + ": " + array1[j]);
}
int[] array2 = new int[i];
System.out.println("\n" + "Organized Array: ");
for (int j = 0; j < i; j++) {
int temp;
boolean organized = false;
while (organized == false) {
organized = true;
for (i = 0; i < array1.length - 1; i++) {
if (array1[i] > array1[i + 1]) {
temp = array1[i + 1];
array1[i + 1] = array1[i];
array1[i] = temp;
organized = false;
}
}
}
scan.close();
}
for (i = 0; i < array1.length; i++) {
System.out.println(array1[i]);
}
}