?
Solved

Sorting

Posted on 2004-03-25
36
Medium Priority
?
261 Views
Last Modified: 2010-03-31
To all,
           I have an array of String and an array of number. They are two different array.  Suppose I need to make String[0] contain value number[0] and so on. How can I make the link between them so that I can perform sorting according to the array of number? Thank you.  
0
Comment
Question by:castle_ckm
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 15
  • 12
  • 3
  • +3
36 Comments
 
LVL 37

Expert Comment

by:zzynx
ID: 10675735
>> Suppose I need to make String[0] contain value number[0] and so on.
Don't understand.
An example would be great
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 10675780
>> Suppose I need to make String[0] contain value number[0]

You mean to say something like:

stringArray[i] = Integer.toString ( numberArray[i] ) ; // assuming you have an integer-array

??
0
 
LVL 16

Expert Comment

by:krakatoa
ID: 10675781
String[] strA = new String[10];

int[] intA = {2,5,7,9,1,4,3,6,8,10};

Arrays.sort(intA);

for(int a=0;a<strA.length;a++){

strA[a] = new String(String.valueOf(intA[a]));

}

for(int a=0;a<strA.length;a++){

System.out.println(strA[a]);
}
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 37

Expert Comment

by:zzynx
ID: 10675788
Do you mean this?

Original Array = "Item 0", "Item 1" "Item 2", "Item 3"
Number array   = 1    2     0     3

must give ==>

Sorted array   = "Item 1", "Item 2" "Item 0", "Item 3"
0
 
LVL 37

Expert Comment

by:zzynx
ID: 10675796
So you need some kind of sort() function with as input the two arrays?
Then after the function the array is sorted?
Is that the Q?
0
 
LVL 37

Expert Comment

by:zzynx
ID: 10676483
If it is,

String[] strA = { "Item 0", "Item 1", "Item 2", "Item 3" };
int[] intA = {1,2,0,3};

String[] strSortedA = new String[4];
for (int i=0; strA.length; i<++)
    strSordtedA[i] = strA[ intA[i] ];
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 10679153
>> I need to make String[0] contain value number[0] and  

I guess he just wants the numbers to be sorted and stored in a String array in String-form, like krakatoa has done.
0
 
LVL 16

Expert Comment

by:krakatoa
ID: 10679565
>> I guess  ...

irony really: we, the people who are meant to supply the answers, often end up asking the most. ;)
0
 
LVL 24

Expert Comment

by:sciuriware
ID: 10680797
I think you want to couple those 2 arrays so that you can do everything,
like sorting, on the 2 together, well .....

How about ONE array of objects, each with a String and an int?

You can sort the array of objects with the JAVA in-built collections sort,
just by supplying a Comparator class that sorts on the Strings, or, on the integers.

In other words: whenever you must combine datasets, make ONE compound dataset!

For instance: it is unwise to keep one array of names, one array of streets and one array of cities,
   create ONE array of Addresses ....

;JOOP!
0
 
LVL 16

Expert Comment

by:krakatoa
ID: 10680847
Mind you, what would probably be even better is just using one array - the String[], and sorting that! Sounds too simple to be true. ;))
0
 

Author Comment

by:castle_ckm
ID: 10683614
To all,
       Thank you for the reply. Sorry for my misunderstand question. Here I will explain my problem.

I have two array
String [5] strA = {"name1","name2","name3","name4","name5"};
int [5] numA = {10, 7, 9, 6, 8};

I want to make link between this two array so name1 has value 10, name2 has value 7, name3 has value 9, name4 has value 6, name5 has value 8. Then I need to perform descending sorting base on numA. The output should be like this:

"name1","name3","name5","name2","name4"

Thank you.
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 10684311
Use some simple selection-sort or bubble-sort algorithm:

for ( int i = 0 ; i < numA.length - 1 ; i ++ )
  for ( int j = i + 1 ; j < numA.length ; j ++ )
    if ( numA[i] > numA[j] )
    {
      int temp = numA[i] ;
      numA[i] = numA[j] ;
      numA[j] = temp ;
      String sTemp = strA[i] ;
      strA[i] = strA[j] ;
      strA[j] = sTemp ;

    }
0
 
LVL 16

Expert Comment

by:gnoon
ID: 10684721
I think this example may appropriate with your want, but it's ascendent sorting.

import java.util.Arrays;
public class Sort {
    public static void main(String[] args) {
        Data data[] = { new Data(10,"name1"),new Data(7,"name2"),new Data(9,"name3"),
                               new Data(6,"name4"),new Data(8,"name5")
                             };
        System.out.println("Before sort:");     printArray(data);
        System.out.println("\n");                   Arrays.sort(data); // sorting
        System.out.println("After sort:");       printArray(data);
    }
    public static void printArray(Object []data) {
        for(int i=0;i<data.length;i++) {
            System.out.print(data[i]+" ");
        }
    }
}

class Data implements Comparable {
    int num;
    String str;
    Data(int num, String str) {
        this.num = num;
        this.str = str;
    }
    int getNum() {
        return num;
    }
    public int compareTo(Object o) {
        if(!(o instanceof Data)) return this.compareTo(o);
        return (num-((Data)o).getNum());
    }
    public String toString() {
        return "["+num+","+str+"]";
    }
}
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 10684744
Just noticed that you want it in descending order. In that case, just change:

>> if ( numA[i] > numA[j] )

- in my code, to:

if ( numA[i] < numA[j] )
0
 
LVL 16

Expert Comment

by:gnoon
ID: 10684926
With my code, just change

    public int compareTo(Object o) {
        if(!(o instanceof Data)) return this.compareTo(o);
        return (num-((Data)o).getNum());
    }

to

    public int compareTo(Object o) {
        if(!(o instanceof Data)) return -this.compareTo(o);
        return -(num-((Data)o).getNum());
    }

to sort in descending order.

0
 
LVL 37

Expert Comment

by:zzynx
ID: 10685034
What about this (shorter) one:

String strA[] = {"name1","name2","name3","name4","name5"};
int numA[] = {10, 7, 9, 6, 8};

Map map = new HashMap();
for (int i=0; i<5; i++)
   map.put(new Integer(numA[i]), strA[i]);

Arrays.sort(numA);

String strASorted[] = new String[5];
for (int i=4; i>=0; i--)
   strASorted[4-i] = (String)map.get(new Integer(numA[i]));
0
 
LVL 37

Expert Comment

by:zzynx
ID: 10685043
Afterwards:

System.out.println("Unsorted:");
for (int i=0; i<5; i++)
    System.out.print(strA[i]+"-");
System.out.println("");
System.out.println("Sorted:");
for (int i=0; i<5; i++)
System.out.print(strASorted[i]+"-");

returns

Unsorted:
name1-name2-name3-name4-name5-
Sorted:
name1-name3-name5-name2-name4-
0
 

Author Comment

by:castle_ckm
ID: 10702119
Dear All,
         Actually I need to sort double value instead of int value. The method provide by gnoon can sort integer value well but for double value with decimal point, it fail to sort. Please help. Thank you


0
 
LVL 37

Expert Comment

by:zzynx
ID: 10702136
In my comment

change

      int numA[] = {10, 7, 9, 6, 8};

by

      double numA[] = {10.0, 7.1, 9.5, 6.4, 8.5};
0
 
LVL 37

Accepted Solution

by:
zzynx earned 75 total points
ID: 10702140
More complete:

String strA[] = {"name1","name2","name3","name4","name5"};
double numA[] = {10.0, 7.1, 9.5, 6.4, 8.5};

Map map = new HashMap();
for (int i=0; i<5; i++)
   map.put(new Double(numA[i]), strA[i]);

Arrays.sort(numA);

String strASorted[] = new String[5];
for (int i=4; i>=0; i--)
   strASorted[4-i] = (String)map.get(new Double(numA[i]));
0
 
LVL 37

Expert Comment

by:zzynx
ID: 10702152
>> Actually I need to sort double value instead of int value
Rather late to tell us, no?
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 10702313
Or:

Make int [] numA as double[] numA and try my code.
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 10702381
Also:

>> int temp = numA[i] ;

would be:

float temp = numA[i] ;

0
 
LVL 30

Expert Comment

by:Mayank S
ID: 10702385
Aaarrrgh~!

>> float temp = numA[i] ;

double temp = numA[i] ;
0
 

Author Comment

by:castle_ckm
ID: 10702477
Dear All,

        For the output I need to display both String and double value. For example:
        String[] strA ={"num1", "num2", "num3", "num4", "num5"};
        Double[] val = {10.4, 8.5, 9.2, 6.1, 7.5};
The output need to be in:
        (num1, 10.4), (num3, 9.2), (num2, 8.5), (num5, 7.5), (num4, 6.1)

For zzynx method can display the String value only.
0
 
LVL 37

Expert Comment

by:zzynx
ID: 10702494
Hey man, you have the numbers in your *sorted* array.
Just print them.

PS. ... and that all for 25 points?
8°/
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 10702503
>> Double[] val = {10.4, 8.5, 9.2, 6.1, 7.5};

Make it: double[] val = {10.4, 8.5, 9.2, 6.1, 7.5};

Have you tried the code that I posted?

for ( int i = 0 ; i < val.length - 1 ; i ++ )
  for ( int j = i + 1 ; j < val.length ; j ++ )
    if ( val[i] > val[j] )
    {
      double temp = val[i] ;
      val[i] = val[j] ;
      val[j] = temp ;
      String sTemp = strA[i] ;
      strA[i] = strA[j] ;
      strA[j] = sTemp ;

    }

After that, you can print it using:

for ( int i = 0 ; i < val.length ; i ++ )
{
  System.out.print ( "(" + strA[i] + ", " + val[i] + ")" ) ;

  if ( i < val.length - 1 )
    System.out.print ( ", " ) ; // end if

} // end for
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 10702507
>> and that all for 25 points?

Really worth a thought.
0
 
LVL 37

Expert Comment

by:zzynx
ID: 10702509
for (int i=4; i>=0; i--) {
   strASorted[4-i] = (String)map.get(new Double(numA[i]));
   System.out.print( "(" + strASorted[4-i], + ",' + numA[i] + ")" );
}
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 10702547
>>  if ( val[i] > val[j] )

Sorry, that would be:  if ( val[i] < val[j] ) for descending order.
0
 
LVL 37

Expert Comment

by:zzynx
ID: 10702568
First think, then type.
;°))
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 10702576
It was just a copy-paste of the first code that I posted. Then I realized that he said later that he wants it in descending order. I wish that questioners tell exactly what they want right at the start.
0
 
LVL 37

Expert Comment

by:zzynx
ID: 10702583
>> I wish that questioners tell exactly what they want right at the start.
LOL
0
 
LVL 37

Expert Comment

by:zzynx
ID: 10702587
... and assign/increment points according to ours efforts
;)
0
 
LVL 37

Expert Comment

by:zzynx
ID: 10702934
Thanks for accepting, but why a B grade?
My code does all you asked for, doesn't it?

I think I'll note you in my book of stingy questioners
;)
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 10702973
http://www.experts-exchange.com/help/closing.jsp - to know how to close questions.
0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:
This video teaches viewers about errors in exception handling.
Suggested Courses
Course of the Month8 days, 18 hours left to enroll

764 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question