How do I reverse the Sort? - java

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)

Related

Sort Array (DONE) and show original index (HALF INCORRECT?)

I have to sort an array using a sorting algorithm and show in which index the values were originally placed. (see expected result vs actual result: https://i.imgur.com/GpIpkPE.png).
I managed to sort correctly the values. BUT the index is HALF correct? Which is confusing me.
public static void sortNumbers(double[] averageNotes) {
for (int i = 0; i < averageNotes.length; i++) {
double max = averageNotes[i];
int maxId = i;
for (int j = i+1; j < averageNotes.length; j++) {
if (averageNotes[j] > max) {
max = averageNotes[j];
maxId = j;
}
}
double temp = averageNotes[i];
averageNotes[i] = max;
averageNotes[maxId] = temp;
System.out.println(averageNotes[i] + " (" + maxId + ")");
}
Any help is highly appreciated. Thank you.
Use an extra array for your indices and sort simultaneously:
public static void sortNumbers(double[] averageNotes) {
//create an array for your indices
int[] indices = new int[averageNotes.length];
//fill indices
for (int i = 0; i < averageNotes.length; i++) {
indices[i] = i;
}
//sort both arrays simultaneously
for (int i = 0; i < averageNotes.length; i++) {
for (int j = i+1; j < averageNotes.length; j++) {
if (averageNotes[i] < averageNotes[j]) {
double temp = averageNotes[i];
averageNotes[i] = averageNotes[j];
averageNotes[j] = temp;
int t = indices[i];
indices[i] = indices[j];
indices[j] = t;
}
}
}
//print
for (int i = 0; i < averageNotes.length; i++) {
System.out.println(averageNotes[i] + " (" + indices[i] + ")");
}
}

Java - Find the row and column with the max sum

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

Sorting multidimensional array without sort method?

I was tasked with creating a 2D array (10-by-10), filling it with random numbers (from 10 to 99), and other tasks. I am, however, having difficulty sorting each row of this array in ascending order without using the array sort() method.
My sorting method does not sort. Instead, it prints out values diagonally, from the top leftmost corner to the bottom right corner. What should I do to sort the numbers?
Here is my code:
public class Program3
{
public static void main(String args[])
{
int[][] arrayOne = new int[10][10];
int[][] arrayTwo = new int[10][10];
arrayTwo = fillArray(arrayOne);
System.out.println("");
looper(arrayTwo);
System.out.println("");
sorter(arrayTwo);
}
public static int randomRange(int min, int max)
{
// Where (int)(Math.random() * ((upperbound - lowerbound) + 1) + lowerbound);
return (int)(Math.random()* ((max - min) + 1) + min);
}
public static int[][] fillArray(int x[][])
{
for (int row = 0; row < x.length; row++)
{
for (int column = 0; column < x[row].length; column++)
{
x[row][column] = randomRange(10,99);
System.out.print(x[row][column] + "\t");
}
System.out.println();
}
return x;
}
public static void looper(int y[][])
{
for (int row = 0; row < y.length; row++)
{
for (int column = 0; column < y[row].length; column++)
{
if (y[row][column]%2 == 0)
{
y[row][column] = 2 * y[row][column];
if (y[row][column]%10 == 0)
{
y[row][column] = y[row][column]/10;
}
}
else if (y[row][column] == 59)
{
y[row][column] = 99;
}
System.out.print(y[row][column] + "\t");
}
System.out.println();
}
//return y;
}
public static void sorter(int[][] z)
{
int temp = 0;
int tempTwo = 0;
int lowest;
int bravo = 0;
int bravoBefore = -1;
for (int alpha = 0; alpha < z.length; alpha++)
{
//System.out.println(alpha + "a");
lowest = z[alpha][bravoBefore + 1];
bravoBefore++;
for (bravo = alpha + 1; bravo < z[alpha].length; bravo++)
{
//System.out.println(alpha + "b");
temp = bravo;
if((z[alpha][bravo]) < lowest)
{
temp = bravo;
lowest = z[alpha][bravo];
//System.out.println(lowest + " " + temp);
//System.out.println(alpha + "c" + temp);
tempTwo = z[alpha][bravo];
z[alpha][bravo] = z[alpha][temp];
z[alpha][temp] = tempTwo;
//System.out.println(alpha + "d" + temp);
}
}
System.out.print(z[alpha][bravoBefore] + "\t");
}
/*
for (int alpha = 0; alpha < z.length; alpha++)
{
for (int bravo = 0; bravo < z.length - 1; bravo++)
{
if(Integer.valueOf(z[alpha][bravo]) < Integer.valueOf(z[alpha - 1][bravo]))
{
int[][] temp = z[alpha - 1][bravo];
z[alpha-1][bravo] = z[alpha][bravo];
z[alpha][bravo] = temp;
}
}
}
*/
}
}
for(int k = 0; k < arr.length; k++)
{
for(int p = 0; p < arr[k].length; p++)
{
least = arr[k][p];
for(int i = k; i < arr.length; i++)
{
if(i == k)
z = p + 1;
else
z = 0;
for(;z < arr[i].length; z++)
{
if(arr[i][z] <= small)
{
least = array[i][z];
row = i;
col = z;
}
}
}
arr[row][col] = arr[k][p];
arr[k][p] = least;
System.out.print(arr[k][p] + " ");
}
System.out.println();
}
Hope this code helps . Happy coding
let x is our unsorted array;
int t1=0;
int i1=0;
int j1=0;
int n=0;
boolean f1=false;
for(int i=0;i<x.length;i++){
for(int j=0;j<x[i].length;j++){
t1=x[i][j];
for(int m=i;m<x.length;m++){
if(m==i)n=j+1;
else n=0;
for(;n<x[m].length;n++){
if(x[m][n]<=t1){
t1=x[m][n];
i1=m;
j1=n;
f1=true;
}
}
}
if(f1){
x[i1][j1]=x[i][j];
x[i][j]=t1;
f1=false;
}
}
}
//now x is sorted; "-";

Already sorted array

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

Checking For Repeats

I'm trying to write code that checks for repeat numbers in an array. If numbers repeat within the same row, it should generate another random number to replace the number. This is my class/method that is meant to accomplish this goal:
import java.util.*;
public class NoRepeats
{
public static void clean(int ticks[][])
{
for(int i = 0; i < ticks.length; i++)
{
for(int j = 0; j < ticks[0].length; j++)
{
nums[j] = ticks[i][j];
}
for(int k = 0; k < nums.length; k++)
{
for(int count = k + 1; count < nums.length; count++)
{
int othNums = nums[count];
while(true)
{
if(nums[k] == othNums)
{
System.out.print("\n\n Repeat:" + nums[k] + k + " " + othNums + "\tTicket Number: " + (i+1) +"\n\n\n");
nums[k] = 1 + rndm.nextInt(48);
for(int counter = count; counter < nums.length; counter++)
{
int othNums2 = nums[count];
if(nums[k] == othNums2)
{
System.out.print("\n\n Repeat NUM2:" + nums[k] + " " + othNums2 + "\tTicket Number: " + (i+1) +"\n\n\n");
nums[k] = 1 + rndm.nextInt(48);
}
}
for(int l = 0; l < k; l++)
{
int othNums3 = nums[l];
if(nums[k] == othNums3)
{
System.out.print("\n\n RepeatNUM2: " + nums[k] + " " + othNums3 + "\tTicket Number: " + (i+1) +"\n\n\n");
nums[k] = 1 + rndm.nextInt(48);
}
}
}
else
{
break;
}
}
count++;
}
}
for(int q = 0; q < nums.length; q++)
{
ticks[i][q] = nums[q];
}
count = 0;
}
}
public static int nums[] = new int[6];
public static int count = 1;
public static Random rndm = new Random();
public static int numsMatched[] = new int[100];
}
For some reason, there are still matches and I don't know why. Can anyone find what I've done wrong?
You're incrementing count twice and thus skip entries:
for(int count = k + 1; count < nums.length; count++) //<- increment 1
{
int othNums = nums[count];
while(true)
{
//snip
}
count++; //<- increment 2
}
The problem probably originates from the fact that you have a static variable which is also called count and which will be shadowed by the count defined in the loop:
public static int count = 1;
So either remove the second increment or rename one of the variables.

Categories