# Identify and swap two numbers in an array

• (3 Pages)
• 1
• 2
• 3

## 41 Replies - 18479 Views - Last Post: 08 March 2012 - 05:36 PMRate Topic: //<![CDATA[ rating = new ipb.rating( 'topic_rate_', { url: 'http://www.dreamincode.net/forums/index.php?app=forums&module=ajax&section=topics&do=rateTopic&t=252319&amp;s=0d6cbb91c9573b0c3eecdfef323f55e0&md5check=' + ipb.vars['secure_hash'], cur_rating: 0, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

### #1 htek38

Reputation: 1
• Posts: 65
• Joined: 09-October 11

# Identify and swap two numbers in an array

Posted 21 October 2011 - 07:59 AM

Here is my assignment:

I have to create a ten element array with numbers between 0 and 99 inclusive, and then identify the largest and smallest numbers in the array and their locations. I then need to swap those two numbers, and redisplay the array showing those two elements in their swapped locations. The problem I am running into, is do I use a method for the identification of the two numbers (and if so, is a brand new array created in the method) or should I just identify and swap programmatically (e.g. not use a method); and then how would I accomplish either of these?

Here is the code that I have so far:

```/*
* Create a ten element array with random numbers between
* 0 and 99, identify the largest and smallest elements and
* their locations and swap them.
*/

package swapmaxmin;

public class SwapMaxMin {

public static void main(String[] args) {

int [] mySwap = new int[10]; //Create a ten element array

int i;

for (i = 0; i < mySwap.length; i++)
mySwap[i] = (int)(Math.random() * 99); //Create ten random numbers between 0 and 99

for (i = 0; i < mySwap.length; i++)

System.out.println("mySwap[" + i + "] = " + mySwap[i]); //Print original array showing elements and position

}

public static int minMaxMethod(int myMin, int myMax) { //As you can see I started creating a method but stopped, not being sure if it would create a new array and how that would be handled if that is indeed what it would or should do.

int findNums;

}

}
```

Is This A Good Question/Topic? 0

## Replies To: Identify and swap two numbers in an array

### #2 blackcompe

• D.I.C Lover

Reputation: 1159
• Posts: 2,547
• Joined: 05-May 05

## Re: Identify and swap two numbers in an array

Posted 21 October 2011 - 08:29 AM

Pass the array only. You don't need to pass the min and max, your method name implies that you'll find them and swap them.

```public static int swapMinMax(int[] ar) {
```

### #3 macosxnerd101

• Games, Graphs, and Auctions

Reputation: 12297
• Posts: 45,396
• Joined: 27-December 08

## Re: Identify and swap two numbers in an array

Posted 21 October 2011 - 08:41 AM

Or better, make a swap() method, and have another component responsible for finding the max and min indices. That way, swap() is more reusable.
```public void swap(int[] x, int one, int two){
//code
}

```

### #4 Psyguy

• D.I.C Regular

Reputation: 84
• Posts: 365
• Joined: 12-January 11

## Re: Identify and swap two numbers in an array

Posted 21 October 2011 - 08:41 AM

You can do it any way you want, that's one of the great things about programming! If instead, you are asking what I would do:

Create a method to find the lowest numbers index
Create a method to find the highest numbers index
Create a method that takes an array and both indices then swaps the values at those indices.

Your swapLowAndHigh method should look a little like this
```int low;
int high;

low = findLowIndex(myArray);
high = findHighIndex(myArray);
swapNums(myArray, low, high);

```

Edit: forgot the line terminator (I don't usually do java)

This post has been edited by Psyguy: 21 October 2011 - 08:43 AM

### #5 htek38

Reputation: 1
• Posts: 65
• Joined: 09-October 11

## Re: Identify and swap two numbers in an array

Posted 21 October 2011 - 09:03 AM

blackcompe, on 21 October 2011 - 09:29 AM, said:

Pass the array only. You don't need to pass the min and max, your method name implies that you'll find them and swap them.

```public static int swapMinMax(int[] ar) {
```

This is a good idea...I think I understand what you are advising.

macosxnerd101, on 21 October 2011 - 09:41 AM, said:

Or better, make a swap() method, and have another component responsible for finding the max and min indices. That way, swap() is more reusable.
```public void swap(int[] x, int one, int two){
//code
}

```

This is also a good idea...but I am not sure if I understand what I would do with the variables that are created.

Psyguy, on 21 October 2011 - 09:41 AM, said:

You can do it any way you want, that's one of the great things about programming! If instead, you are asking what I would do:

Create a method to find the lowest numbers index
Create a method to find the highest numbers index
Create a method that takes an array and both indices then swaps the values at those indices.

Your swapLowAndHigh method should look a little like this
```int low;
int high;

low = findLowIndex(myArray);
high = findHighIndex(myArray);
swapNums(myArray, low, high);

```

Edit: forgot the line terminator (I don't usually do java)

Couldn't I do all of this with a single method, instead of creating multiple methods each for a single operation?

### #6 Notorion

• D.I.C Regular

Reputation: 35
• Posts: 378
• Joined: 17-February 09

## Re: Identify and swap two numbers in an array

Posted 21 October 2011 - 09:21 AM

Quote

Couldn't I do all of this with a single method, instead of creating multiple methods each for a single operation?

Yes! You absolutely could.
Although, it is better (in the end) to do it they way they are suggesting to you.
Think about this. Are you possibly going to need to use a swap function again in a future program or in this program, but it might not be the highest and lowest numbers? You might need to. Therefore, if you did it all in one without making them into functions you would have to rewrite a more simple swap function even though you already wrote a big one.

The other posters are advising you to break down the code into chunks. Making them small building blocks you can use over and over again to build a house. Also, with the other two functions like findMin and findMax. Sometimes you don't want to swap them sometimes you might. What if you don't want to swap them, and just find them? See if you just build a findMin, findMax and Swap() functions you could easily integrate all 3, and still have just these functions in case you wanted to swap other elements.

My comment to your original post was going to be a simple:
"Make sure you pass your array by reference to the swap function instead of passing it by value".

This post has been edited by Notorion: 21 October 2011 - 09:22 AM

### #7 macosxnerd101

• Games, Graphs, and Auctions

Reputation: 12297
• Posts: 45,396
• Joined: 27-December 08

## Re: Identify and swap two numbers in an array

Posted 21 October 2011 - 10:26 AM

Quote

This is also a good idea...but I am not sure if I understand what I would do with the variables that are created.

The first param in my method is the array, and the second and third params are the indices of the elements to swap.

### #8 Psyguy

• D.I.C Regular

Reputation: 84
• Posts: 365
• Joined: 12-January 11

## Re: Identify and swap two numbers in an array

Posted 21 October 2011 - 10:40 AM

Notorion, on 21 October 2011 - 09:21 AM, said:

Quote

Couldn't I do all of this with a single method, instead of creating multiple methods each for a single operation?

Yes! You absolutely could.
Although, it is better (in the end) to do it they way they are suggesting to you.
Think about this. Are you possibly going to need to use a swap function again in a future program or in this program, but it might not be the highest and lowest numbers? You might need to. Therefore, if you did it all in one without making them into functions you would have to rewrite a more simple swap function even though you already wrote a big one.

The other posters are advising you to break down the code into chunks. Making them small building blocks you can use over and over again to build a house. Also, with the other two functions like findMin and findMax. Sometimes you don't want to swap them sometimes you might. What if you don't want to swap them, and just find them? See if you just build a findMin, findMax and Swap() functions you could easily integrate all 3, and still have just these functions in case you wanted to swap other elements.

My comment to your original post was going to be a simple:
"Make sure you pass your array by reference to the swap function instead of passing it by value".

This is exactly the point I am trying to convey to you. As a professional programmer or Software Engineer, you will want to have the most reusable code you can make. The more methods you have available to you that do what you need to do, the less time you will spend doing things you have already done before. Your employer will love you for it and you will spend more time doing new stuff instead of repeating old stuff.

### #9 htek38

Reputation: 1
• Posts: 65
• Joined: 09-October 11

## Re: Identify and swap two numbers in an array

Posted 21 October 2011 - 10:57 AM

I figured out how to identify the largest and smallest numbers in the array. I am having trouble though printing those values and also correctly printing the location where they are found in the array.

Here is my current code:

```/*
* Create a ten element array with random numbers between
* 0 and 99, identify the largest and smallest elements and
* their locations and swap them.
*/

package swapmaxmin;

public class SwapMaxMin {

public static void main(String[] args) {

int [] mySwap = new int[10]; //Create a ten element array

int i;
int max, min;

for (i = 0; i < mySwap.length; i++)
mySwap[i] = (int)(Math.random() * 99); //Create ten random numbers between 0 and 99

for (i = 0; i < mySwap.length; i++)

System.out.println("mySwap[" + i + "] = " + mySwap[i]); //Print original array showing elements and position

max = mySwap[0];
min = mySwap[0];

for (i = 0; i < mySwap.length; i++) { //Identify the largest and smallest numbers

if (mySwap[i] > max) {
max = mySwap[i];
}

else if (mySwap[i] < min) {
min = mySwap[i];
}
}

System.out.println("The largest number is " + max + " and at [" + i + "]"); //This line is correctly printing the highest value, but it is printing location 10 instead of the correct location
System.out.println("The smallest number is " + min); //This one will be finished once I have the print command for the large number printing correctly
}

}
```

Now that I think about it, I maybe could take the for loop that identifies the highest and lowest numbers and incorporate them into a method...but how would I pass the array to the method so that I can do that...my textbook isn't that helpful in explaining exactly how this is done (the examples shown are pretty vague).

### #10 macosxnerd101

• Games, Graphs, and Auctions

Reputation: 12297
• Posts: 45,396
• Joined: 27-December 08

## Re: Identify and swap two numbers in an array

Posted 21 October 2011 - 11:04 AM

I would just store the max and min indices.
```max <-- 0
min <-- 0

for i = 1, i < arr.length, i++
if arr[i] > arr[max]
max = i
else if arr[i] < arr[min]
min = i

```

### #11 blackcompe

• D.I.C Lover

Reputation: 1159
• Posts: 2,547
• Joined: 05-May 05

## Re: Identify and swap two numbers in an array

Posted 21 October 2011 - 11:13 AM

Quote

Now that I think about it, I maybe could take the for loop that identifies the highest and lowest numbers and incorporate them into a method...but how would I pass the array to the method so that I can do that...my textbook isn't that helpful in explaining exactly how this is done (the examples shown are pretty vague).

```main()
{
int ar[];//populate
int min = min(ar);
int max = max(ar);
}
static int min(int ar[])
{
int min = ar[0];//Integer.MAX_VALUE
for(int elem: ar)if(elem < min)min = elem;
}

```

This post has been edited by blackcompe: 21 October 2011 - 11:14 AM

### #12 htek38

Reputation: 1
• Posts: 65
• Joined: 09-October 11

## Re: Identify and swap two numbers in an array

Posted 21 October 2011 - 11:23 AM

macosxnerd101, on 21 October 2011 - 12:04 PM, said:

I would just store the max and min indices.
```max <-- 0
min <-- 0

for i = 1, i < arr.length, i++
if arr[i] > arr[max]
max = i
else if arr[i] < arr[min]
min = i

```

Thank you for the code example.

I tried your code example, but it is not displaying the correct high and low number in the array...is this code example using the highest and lowest number and displaying their indices instead of the number value itself?

If so, I need the actual number value itself rather than the indices of the numbers.

### #13 macosxnerd101

• Games, Graphs, and Auctions

Reputation: 12297
• Posts: 45,396
• Joined: 27-December 08

## Re: Identify and swap two numbers in an array

Posted 21 October 2011 - 11:28 AM

So access arr[max] after the fact. You have the index, and can access the value. You have more information than just with the value.

### #14 htek38

Reputation: 1
• Posts: 65
• Joined: 09-October 11

## Re: Identify and swap two numbers in an array

Posted 21 October 2011 - 02:09 PM

Ok. so I have the code for the first portion of my assignment written so that I can access the highest and lowest number.

Now I need to be able print the array location for both of those numbers. There is a note in the code next to the print lines for this. How can I reference the array location for my print lines?

Here is my code so far:

```package swapmaxmin;

public class SwapMaxMin {

public static void main(String[] args) {

int [] mySwap = new int[10]; //Create a ten element array

int i;
int j;
int max, min;

System.out.println("Before the swap: ");

for (i = 0; i < mySwap.length; i++)
mySwap[i] = (int)(Math.random() * 99); //Create ten random numbers between 0 and 99

for (i = 0; i < mySwap.length; i++)

System.out.println("mySwap[" + i + "] = " + mySwap[i]); //Print original array showing elements and position

max = mySwap[0];
min = mySwap[0];

for (j = 0; j < mySwap.length; j++) {

if (mySwap[j] > max) {
max = mySwap[j];

}

else if (mySwap[j] < min) {
min = mySwap[j];

}
}
System.out.print("\n");
System.out.println("The largest number is " + max + " and at [" + " " + "] "); //This displays the largest number in the array...still needs to display the array position
System.out.println("The smallest number is " + min + " and at [" + " " + "] "); //This displays the smallest number in the array...still needs to display the array position
System.out.print("\n");

}

}
```

This post has been edited by htek38: 21 October 2011 - 02:10 PM

### #15 macosxnerd101

• Games, Graphs, and Auctions

Reputation: 12297
• Posts: 45,396
• Joined: 27-December 08

## Re: Identify and swap two numbers in an array

Posted 21 October 2011 - 02:13 PM

Quote

Now I need to be able print the array location for both of those numbers. There is a note in the code next to the print lines for this. How can I reference the array location for my print lines?

I just went over that! Did you not read my posts or something?