Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations sizbut on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Help with how to sort 2 arrays

Status
Not open for further replies.

annie42

Technical User
Nov 18, 2003
1
US
I have the following 2 arrays and need to sort them so the ID number stays with the video it represents.

String[] video = {"Sleepless in Seattle", "You've got mail ", "Wizard of Oz ", "Something about Mary", "Toy Story II "};

int[] IDnum = {453, 845, 2364, 8052, 6250};

Like sort for IDnum but the videos sort the same way.
Sleepless in Seattle - 453
etc.

I know it should be easy and I can get one array to sort but the other one doesn't stay with it. I'm getting frustrated and have asked for help in class but no one seems to answer the question I'm asking. Thanks for any assistance you can give me.

Annie
 
You can make a class "Video" containing the title and the id and make 1 array of "Videos" and sort this array. In this way you can also add extra attributes to the "Video" class.

eg.
Code:
public class Video {
  
  private String title;
  private int id;

  public Video(String title, int id) {
    this.title = title;
    this.id = id;
  }

  ...

}

====
Since this is a class assignment, the rest is up to you.
 
It's probably better to create a class like hologram said, but just for fun .... here it is.
Code:
public class BubbleSort {
	public static void swap(String[] array, int i, int j) {
		String temp = array[i];
		array[i] = array[j];
		array[j] = temp;
	}
	public static void swap(int[] array, int i, int j) {
		int temp = array[i];
		array[i] = array[j];
		array[j] = temp;
	}
	public static void sort(String[] names, int[] ids) {
		int n = names.length;
		for (int i = 0; i < n - 1; i++) {
			for (int j = 0; j < n - 1 - i; j++) {
				if (names[j + 1].compareToIgnoreCase(names[j]) < 0) {
					swap(names, j, j+1);
					swap(ids, j, j+1);
				}
			}
		}
	}
	public static void main(String[] args) throws Exception {
		String[] video = {&quot;Sleepless in Seattle&quot;, &quot;You've got mail     &quot;, &quot;Wizard of Oz        &quot;, &quot;Something about Mary&quot;, &quot;Toy Story II        &quot;};
		int[] IDnum = {453, 845, 2364, 8052, 6250};
		BubbleSort.sort(video, IDnum);
		for (int i = 0; i < video.length; i++) {
			System.out.println(IDnum[i]+&quot;: &quot;+video[i]);
		}
	}
}[code]

Sean McEligot
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top