sorted array in java using swap methods - java

My problem is when I sort a list it will get the last element of the array wrong, ending up with it at the beginning of the array. In my example it fails to sort the last element which is 9, ending up printed first ahead of small numbers such as 0 and 1. Here is my code:
public class ty {
public static void main(String[]argus){
int []numbers={45,23,34,545,56,23,4,1,66,0,9};
int j;
for( int i=0;i<numbers.length;i+=1){
int first=0;
for(j=0;j<=i;j+=1){
if(numbers[j]>=first){
first=numbers[j];
numbers[j]=numbers[i];
numbers[i]=first;}
}//inner loop
}//first loop
for(int i=0;i<numbers.length;i+=1){
System.out.print(numbers[i]+" ");}
}
}
//the output is 9 0 1 4 23 23 34 45 56 66 545
As you see, they are in order except for the 9 at the start which is out of place.

You have the wrong output as a result of a logical error. You have mistakes in the Selection sort technique. Here's how to do it:
int []numbers={45,23,34,545,56,23,4,1,66,0,9};
for(int i=0; i<numbers.length-1; i+=1){
int m = i;
for(int j=i+1; j<numbers.length; j+=1){
if(numbers[m]>numbers[j])
m = j;
}
int temp = numbers[m];
numbers[m] = numbers[i];
numbers[i] = temp;
}
for(int i=0; i<numbers.length; i+=1)
System.out.print(numbers[i]+"\t");
This will work correctly and give the output:
0 1 4 9 23 23 34 45 56 66 545

Related

I cant find a way to get the Maximum number in the array (Ar.getMax()). My output is constantly 0

Im trying to get the maximum number in the array, using the function getMax(), but the output is always 0.
When input is: 12 87 3 10 55 69 40
Result should be: 69
Instead result is: 0
public int getMax()
{
int x=1;
int y=0;
for(int i=0; i<size; i++)
{
if(i!=size-1)
{
if(arr[i]>arr[x])
{
y=arr[i];
x++;
}
}
}
return y;
}
Simply set the default maximum value to the first value in the array. Then, iterate thru the array comparing that value to the next one in the array. If is is larger then assign it to max. Continue to the end of the array.
As 89 is larger, I think you want the local maximum of the longest non-decreasing subsequence in the array. The problem is not well formulated, so probably no homework.
array: 12 87 3 10 55 69 40
sequences: 12 87
3 10 55 *69* answer
40
int maxOfLongestSubsequence(int[] a) {
int maxSeqLength = 0;
int max = Integer.MIN_VALUE;
int seqStart = -1;
for (int i = 0; i <= a.length; ++i) {
if (i == 0 || i == a.length - 1 || a[i] < a[i - 1]) { // New subsequence
int seqLength = i - seqStart;
if (i - seqLength > maxSeqLength) {
maxSeqLength = seqLength;
max = a[i - 1];
}
seqStart = i;
}
}
return max;
}
Formulate the problem. Depict the data as I did. And program it out.
You can pick the max of an int array like this:
int [] numbers = new int[]{12,87,3,10,55,69,40};
int max = numbers[0];
for(int current : numbers) {
max = current >= max ? current : max;
}
System.out.println(max);

Home work about Matrix containing another matrix ( Check if true or false)

So the instructions are to create a matrix 10x10 and randomize values between 1~20 for each index
Then ask the user to enter 6 numbers between 1~20, and use those numbers to create
another 2x3 Matrix.
Then the program has to check if the 10x10 matrix contains the 2x3 matrix from the user.
Also i'm not allowed to use functions.
Example for input:
Enter the1 number in the matrix: 17
Enter the2 number in the matrix: 17
Enter the3 number in the matrix: 17
Enter the4 number in the matrix: 5
Enter the5 number in the matrix: 13
Enter the6 number in the matrix: 14
Output:
The random matrix:
14 14 3 18 2 10 19 10 3 3
2 17 15 16 5 17 7 17 15 10
13 1 3 9 5 4 11 9 1 8
17 14 13 9 8 1 18 3 17 18
12 17 5 14 13 4 16 14 13 4
8 12 8 19 6 5 3 3 14 18
16 16 17 9 9 10 17 3 8 5
13 8 6 17 6 17 17 7 19 5
5 14 6 15 11 11 13 17 17 17
17 13 13 18 11 4 15 5 13 14
The matrix you entered:
17 17 17
5 13 14
The random matrix contains the users matrix.
My Code so far =
int[][] big = new int[10][10];
int[][] small =new int [][] {{the1,the2,the3},{the4,the5,the6}};
for(int i = 0; i < big.length; i++ )
{
for(int j = 0; j < big[i].length; j++)
{
big[i][j]= (int)((Math.random()*20)+1);
}
}
for(int i =0; i < big.length; i++)
{
for(int j = 0; j < big.length; j++)
{
Boolean isEqual=true;
for(int k = 0; k < 2 && isEqual; k++)
{
for(int m = 0; m < 3; m++)
{
if (big[i+k][j+m]!=small[k][m])
{
isEqual=false;
break;
}
}
}
}
}
My general idea was basically running through the indexes of the big matrix while checking for equal numbers, and if one found, the routine continues, otherwise it breaks, and going to the next index in the big matrix.
Your general idea is correct and should work for the described scenario. The only issue you are having is your break statement doesent work as you think.
According to nested loop, if you put break statement in inner loop, compiler will jump out from inner loop and continue the outer loop again. If you need to jump out from the outer loop using break statement given inside inner loop you can use a labelled loop, i.e give your loop a name and use it with the break statement.
In your code above you shold not only breake the inner most loop but also the one above:
public static void main(String[] args) {
int[][] big = new int[10][10];
int[][] small = new int[][]{{12, 13, 14}, {13, 14, 15}};
for (int i = 0; i < big.length; i++) {
for (int j = 0; j < big[i].length; j++) {
big[i][j]= (int)((Math.random()*20)+1);
}
}
// just added this loop to print the random array so you can check the output
for(int[] row : big){
System.out.println(Arrays.toString(row));
}
for(int i = 0; i<big.length-1; i++){
for(int j = 0; j<big[0].length-2; j++){
boolean isEqual = true;
LoopIwannaBreak:for(int k = 0; k<small.length; k++){
for(int m = 0; m<small[0].length; m++){
if(big[i+k][j+m] != small[k][m]){
isEqual = false;
break LoopIwannaBreak;
}
}
}
// added this to tell at which index the match was found
if(isEqual){
System.out.println("found at big["+i+"]["+j+"]");
}
}
}
}

Print out three dimensional array and getting the combined integer value

I´m trying to create a 3 dimensional array which should have three horizontal boxes which two rows and 3 columns in each. As it is the output get me two vertical boxes with 3 rows and 3 columns, I have tried to change the integers around but it seems to just get me in deeper trouble.
And on top of this I´ve been trying to add all the integers in the array to get and print out the mean/average value but I can´t really find/understand how to do this.
int[][][] ett= {{ {10,12,14}, {16,18,20}, {22,24,26} },
{ {11,13,15}, {17,19,21}, {23,25,27} } };
//want this to print out as it looks, three "boxes" with two rows and three columns
for (int i= 0; i<ett.length;i++){
for (int j= 0; j<ett[i].length ;j++){
for (int k=0; k<ett[i][j].length;k++){
System.out.print(ett[i][j][k]+" ");
}
System.out.println();
}
System.out.println();
}
int medel=0;
//medel = all integers in array added, 10+12+14...
// divide medel with number of integers in array (18)
System.out.println("Medelvärdet: "+medel);
}//main
You only have to get rid of one println :
for (int i= 0; i<ett.length;i++){
for (int j= 0; j<ett[i].length ;j++){
for (int k=0; k<ett[i][j].length;k++){
System.out.print(ett[i][j][k]+" ");
}
// System.out.println(); remove this println
}
System.out.println();
}
and you'll get this :
10 12 14 16 18 20 22 24 26
11 13 15 17 19 21 23 25 27
You might want to add spaces between the blocks :
for (int i= 0; i<ett.length;i++){
for (int j= 0; j<ett[i].length ;j++){
for (int k=0; k<ett[i][j].length;k++){
System.out.print(ett[i][j][k]+" ");
}
System.out.print(" ");
}
System.out.println();
}
which will give you this:
10 12 14 16 18 20 22 24 26
11 13 15 17 19 21 23 25 27

For each loop won't print correctly

I'm not sure why this won't print out anything
for (int number : humidity)
{
if (sum < 12)
{
System.out.printf("%6d",humidity[sum]);
sum++;
}
}
Humidity is taken in from a file
Scanner inFileHumid = new Scanner(fileNameHumid);
int [] humidity = new int[length];
Then is set to the array
while (inFileHumid.hasNextInt())
{
humidity[n] = inFileHumid.nextInt( );
n++;
}
and the numbers from the file are 69 67 66 64 66 69 67 67 70 69 69 70 which are the ones I'm trying to get to be printed in my for each loop
You are iterating each number in humidity, but then you ignore those values and test some unrelated sum. I think you want
for (int number : humidity)
{
System.out.printf("%6d", number);
}
Or equivalently,
for (int sum = 0; sum < humidity.length; sum++)
{
System.out.printf("%6d", humidity[sum]);
}
I think you just have a problem indexing into humidity. So this should work.
for (int number : humidity){
if (number < 12) // Look at the value
{
System.out.printf("%6d", number); // Print what is in the array
}
}
Assuming sum is zero before the loop is entered, that code works.
int[] humidity = {1,2,3,4,5,6,7,8,9,0,1,2};
int sum= 0;
for (int number : humidity) {
if (sum < 12) {
System.out.printf("%6d", humidity[sum]);
sum++;
}
}
producing:
1 2 3 4 5 6 7 8 9 0 1 2
So for the code to fail sum must be greater or equal to 12 before the loop is entered.

Two dimensional array bug (can't find it)

I am doing this homework project that produces the pascals triangle but I'm getting an error and I can't find it. I looked it over many times but to me it seems okay, Can someone help me find the bug?
public class PascalsTriangle {
public static void main(String[] args) {
int[][] triangle = new int[11][];
fillIn(triangle);
print(triangle);
}
public static void fillIn(int[][] triangle) {
for (int i = 0; i < triangle.size(); i++) {
triangle[i] = new int[i++];
triangle[i][0] = 1;
triangle[i][i] = 1;
for (int j = 1; j < i; j++) {
triangle[i][j] = triangle[i-1][j-1] + triangle[i-1][j];
}
}
}
public static void print(int[][] triangle) {
for (int i = 0; i < triangle.length; i++) {
for (int j = 0; j < triangle[i].length; j++) {
System.out.print(triangle[i][j] + " ");
}
System.out.println();
}
}
I assume you have already changed your code to use length instead of size as the other answer mentions.
When you call this method:
public static void fillIn(int[][] triangle) {
for (int i = 0; i < triangle.length; i++) {
triangle[i] = new int[i++]; // this line
triangle[i][0] = 1;
The line pointed out above should be:
triangle[i] = new int[i + 1];
When you call i++ the int array will be initialized with length i and then i will be incremented. You are already incrementing i in the declaration of your for loop. So, we take away the ++.
But then we have another problem. You start the loop at i = 0. Then you initialize an array with length 0. Then you add an element to that array. Something doesn't make sense. What you meant to do was to initialize the array as int[i + 1].
Finally the program displays some lines from Pascal's Triangle:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1
1 10 45 120 210 252 210 120 45 10 1
not sure this method exist
triangle.size()
try
triangle.length
instead

Categories

Resources