How to change index of one row in an array to correspond to index of another row in another array?
-
I have to write a program in Java in which user is prompted to enter name of student and scores. My output should display names of student in ascending order of their score. I can sort scores in ascending order but not able to figure out how to change student name sequence based on score. I am creating 2 arrays one for name of student and another for score. I can sort score array but don't know how to sort name array so that score and name match
-
Answer:
Try sorting your grades array manually (i.e. don't use the built-in sort method). As you are sorting your grades array, you will be swapping elements. You should simultaneously swap the elements in your student array. Here's the code. I took the BubbleSort code from GeekPedia[1]: import java.util.*; public class Project2 { public static void main (String [] args) { int[] grades = {99, 70, 66, 98, 82}; String[] students = { "Joe", "Bill", "Harry", "Tom", "Mary" }; System.out.println("Before sort:"); System.out.println(Arrays.toString(gr… System.out.println(Arrays.toString(st… bubbleSort(grades, students); System.out.println("After sort:"); System.out.println(Arrays.toString(gr… System.out.println(Arrays.toString(st… } //note: a is the grades array, b is the students array public static void bubbleSort(int[] a, String[] b) { int out, in; for(out=a.length-1; out>1; out--) for(in=0; in<out; in++) if( a[in] > a[in+1] ) { //swap them int temp = a[in]; a[in] = a[in+1]; a[in+1] = temp; //swap the student names too String stemp = b[in]; b[in] = b[in+1]; b[in+1] = stemp; } } // end bubbleSort() }
D at Yahoo! Answers Visit the source
Related Q & A:
- How to change array elements?Best solution by Stack Overflow
- How to insert data from one table to another?Best solution by Stack Overflow
- How to change Keyboard.Row background?Best solution by Stack Overflow
- How to direct emails from one account to another?Best solution by Yahoo! Answers
- How do I output from one form to another in Visual Basic?Best solution by support.microsoft.com
Just Added Q & A:
- How many active mobile subscribers are there in China?Best solution by Quora
- How to find the right vacation?Best solution by bookit.com
- How To Make Your Own Primer?Best solution by thekrazycouponlady.com
- How do you get the domain & range?Best solution by ChaCha
- How do you open pop up blockers?Best solution by Yahoo! Answers
For every problem there is a solution! Proved by Solucija.
-
Got an issue and looking for advice?
-
Ask Solucija to search every corner of the Web for help.
-
Get workable solutions and helpful tips in a moment.
Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.