Index of sorted array

I have a unsorted array as follows:
array_index = {0 1 2 3 4 5 6 7 8}
array = {1 2 4 3 4 3 4 2 1}
I would like to get the previous index of sorted array as follows:
old_index = {2 4 6 3 5 1 7 0 8}
arrray.sort doesn't return the index the previous index, please help me.

You can do that using by creating an array containing the numbers 0 to n in increasing order and sorting that using a comparator that actually compares the content of the original array at the indices provided to it instead of the values themselves.
But why would you need that? Could you describe your requirement in a broader scope?

Similar Messages

  • Sort array and return indexes

    Hello,
    Is there a java method that would sort an array of doubles and also return the original indexes of the array elements.
    There is Array.sort(myArray), however the method does not give the original indexes.
    Writing a code on sorting and getting the indexes does not sound attractive while java has effective methods to sort.
    Thanks!

    devboris wrote:
    Can you ellaborate more on the code? I have not used a Comparator before.i think he/she means something like this, you can use the Comparator to sort the array post your attempt at sorting the array before asking for more help
    public class TestArray {
        ArrayElement[] myArray = new ArrayElement[10];
        public void populateArray(){
            for(int i = 9;i>=0;i--){
                myArray[i] = new ArrayElement(i,9-i);
        public void sortArray(){
            //leave this to you
        public void printArray(){
            for(int i = 0;i<myArray.length;i++){
                System.out.println("Orig pos is "+myArray.getIndex()+" and value is "+myArray[i].getValue());
    public static void main(String[] args){
    TestArray test = new TestArray();
    test.populateArray();
    test.sortArray();
    test.printArray();
    }//end of class
    class ArrayElement {
    public int index;
    public double value;
    public ArrayElement(int i, double v){
    this.index = i;
    this.value = v;
    public int getIndex(){
    return this.index;
    public double getValue(){
    return this.value;
    }//end of classHope this helps
    Calypso                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Sun C++ std::sort coredump during sorting array of long values

    Hello,
    I got core dump during execution following test program on both Solaris 9 (compile by CC: Sun C++ 5.5 Patch 113817-19 2006/10/13) and Solaris 10 platforms (compile by CC: Sun C++ 5.9 SunOS_sparc Patch 124863-01 2007/07/25).
    Core is dumped during sorting array of about 120k elements of unsigned long types using STL std:sort. The input data is available at link: [file.txt|http://www.savefile.com/files/1924004]
    When I change sorting methods to std::stable_sort program works fine.
    The funny thing is that when I change order of last two values of input data (swap), sorting is successful with std::sort.
    Can anyone tell me if it is Sun C++ compiler bug ?Can I use std::stable_sort method safely?
    Below code:
    #include <iostream.h>
    #include <fstream.h>
    #include <set>
    #include <string>
    int main( int argc, char** argv )
      char readStr[256];
      ifstream file;
      unsigned long *l;
      int i=0;
      l = new unsigned long[119016];
      if (l ==0)
        cout << "Error in allocate memory";
        return -1;
      file.open("file.txt");
      if (!file)
        cout << "Error in openening file";
        return -1;
      while(file.getline(readStr, 256,'\n'))
        cout << readStr<<endl;
        l= atol(readStr);
    cout << l[i]<<endl;
    i++;
    std::sort(l,l+119016); //core dump here!!!
    for (i=0;i<119016;i++)
    cout <<l[i]<<endl;
    file.close();
    delete [] l;
    return( 0 );
    Greetings
    Robert                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    You have run into bug 6588033 "std::sort from libCstd loops", which is fixed in current patches.
    Get the current patches for Sun Studio and also the current patch for the C++ runtime libraries (SUNWlibC patch).
    You can find them here:
    [http://developers.sun.com/sunstudio/downloads/patches/index.jsp]
    Sun C++ 5.5 probably does not have the fix, since it is quite old and falling out of support.
    C++ 5.9 does have the fix.

  • Sorting array

    I know how to sort the array of strings alpha numerically but my problem is that the numerical values will not follow there corresponding strings
    here is the code i am using:
    Harold Timmis
    [email protected]
    Orlando,Fl
    *Kudos always welcome
    Solved!
    Go to Solution.
    Attachments:
    testingfileIO.vi ‏35 KB

    Hi.
    It's nice to have "sorting array" icon.
    But I have problem with programming similar option. I want to sort my sine samples taken in more periods to just one period.
    Beside defining that mycurrent sample should be less than next one, and greater from previous one in one case, I should take in consider that derivation could be positive or negative. While negative derivation, next sample should be less then current and so one.
    Can someone help me with programming?
    I've extracted the first period, and then I have to go trough each sample and compare him. When logic is well,I get the index and putinsert elemt in array.
    I think that I'm having problem with while loops. I don't know where to put them.
    I'm attaching VI. beacuse I'm working on Labview 9.0, I'm attaching also a pic.
    Thanks in advance.
    Attachments:
    resampling.vi ‏89 KB
    Untitled.jpg ‏135 KB

  • I need help with event structure. I am trying to feed the index of the array, the index can vary from 0 to 7. Based on the logic ouput of a comparison, the index buffer should increment ?

    I need help with event structure.
    I am trying to feed the index of the array, the index number can vary from 0 to 7.
    Based on the logic ouput of a comparison, the index buffer should increment
    or decrement every time the output of comparsion changes(event change). I guess I need to use event structure?
    (My event code doesn't execute when there is an  event at its input /comparator changes its boolean state.
    Anyone coded on similar lines? Any ideas appreciated.
    Thanks in advance!

    You don't need an Event Structure, a simple State Machine would be more appropriate.
    There are many examples of State Machines within this forum.
    RayR

  • Index (HHK) sorting issue in Japanese (RoboHelp X3)

    I'm a Japanese localizing engineer who now tries to generate
    a WebHelp with a nicely sorted index in Japanese.
    As I assume that this has been a known issue for double-byte
    languages for a long time, a Japanese index cannot be sorted
    perfectly in a compiled chm or WebHelp. In Japanese, there are
    several types of Japanese characters (Kanji, Katakana, Hiragana).
    Regardless of what type of character a string is typed in, Japanese
    strings should be sorted according to <i>yomi-gana</i>,
    the way each Japanese string pronounces but currently an index gets
    sorted according to the following order (in ASCII code):
    *number
    *alphabet
    *hiragana
    *katanaka
    *kanji... and so on.
    So here I'm trying to do the followings:
    1. In a HHK file, I put <so>...</so> in front of
    every entry where I spell out the pronounciation in each <so>
    segment.
    2. Open the HHK with HTML Workshop, sort the file, and save
    it (I'll get the file sorted according to what I have put in
    <so>..</so>.
    3. Open it with a Text Editor and remove all the
    <so>..</so> entrires.
    4. Put the HHK file in a build folder and generate a
    chm/WebHelp in RoboHelp X3.
    In the 4th step, I don't want RoboHelp to re-sort the HHK but
    it does it automatically. If I can disable the index sorting
    functionality in RoboHelp X3 (the latest version in Japanese) but
    looks like there is no way to do it. If anyone is sure that it's
    not possible to disable the auto-sorting functionality in RoboHelp,
    please let me know so that I can give up witout a sweat.
    By the way, I have tried the alternative for WebHelp that
    skips the 3rd step and removes all the <so>...</so> in
    the files that RoboHelp creates. The result is that everything got
    messed up and some of the contents in the Index couldn't be viewed
    in a browser.
    Thanks.
    Rota.

    Hi Paul
    Have you tried just right-clicking in the index and choosing sort?
    Click the image below to view larger.
    Note that this may require you to temporarily configure Microsoft HTML Help as the primary layout and editing the Project Settings in order to allow the sort function to appear.
    Remember, you press Ctrl+Shift+? to open Project Settings. You then would turn off (or ensure it's turned off) the Binary Index feature.
    Once you have done this, you would then revert any settings that you changed to allow things to work.
    Cheers... Rick
    Helpful and Handy Links
    RoboHelp Wish Form/Bug Reporting Form
    Begin learning RoboHelp HTML 7 or 8 within the day - $24.95!
    Adobe Certified RoboHelp HTML Training
    SorcerStone Blog
    RoboHelp eBooks

  • Removes duplicates from a sorted array without having to create a new array

    Funcation removes duplicates from a sorted array without having to create a new array

    Funcation removes duplicates from a sorted array
    without having to create a new arrayIs a 'funcation' like a vacation but more fun or
    something?LMFAO. You just jumped with both feet on one of my biggest peeves. I've been outed!
    Actual words/phrases I've seen used which I hate with every fiber of my being:
    "Mrs. Freshly's"
    "McFlurry"
    "Freshissimo"
    "Spee-dee"
    "Moons Over My Hammy"
    One of my favorite SNL skits had Will Ferrell leading a panel of movie reviewers (they're the worst for this kind of junk). Each one had some cheesy pun to describe their respective movie. Ferrell topped the show off with his endorsement of "Fantasia 2000 is Fantasgreat!"
    LOL.
    "Come to Slippy Village - it's a FUNCATION!"
    &#167; (runs off, laughing maniacally, head explodes)

  • Exception handling in sorting arrays

    Hi all, I have a problem with the use of the built in java sort fo arrays. My program works on an array with 4 or 5 entities. When I run it in some folders it works but not in others. I get the following error after compilation, where "ResultData" is the class of array to be sorted:Exception in thread "main" java.lang.NullPointerException
    at ResultData.compareTo(TextEdit.java:1215)
    at java.util.Arrays.mergeSort(Arrays.java:1064)
    at java.util.Arrays.mergeSort(Arrays.java:1071)
    at java.util.Arrays.mergeSort(Arrays.java:1072)
    at java.util.Arrays.mergeSort(Arrays.java:1071)
    at java.util.Arrays.mergeSort(Arrays.java:1071)
    at java.util.Arrays.mergeSort(Arrays.java:1071)
    at java.util.Arrays.sort(Arrays.java:1014)
    at java.util.Collections.sort(Collections.java:78)
    [\code]Can any one give a suggestion?                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    Here is the code for the class "ResultData"class ResultData implements Comparable
         String file1;
         String file2;
         double var, var1, var2;
         public ResultData(String f1,String f2,double v, double x, double y)
                   file1= f1; file2=f2;
                   var=v; var1=x; var2=y;
         public String getFile1Name()
              return file1;
         public String getFile2Name()
              return file2;
         public double getVar()
              return var;
         public double getVar1()
              return var1;
         public double getVar2()
              return var2;
         public String toString()
              return file1+"          "+file2+"          "+var+"          "+var1+"          "+var2;
           public int compareTo(Object o)
              ResultData r= (ResultData)o;
              double result = this.getVar()- r.getVar();
              if (result < 0.0)         return -1;
              else if(result > 0.0)     return 1;
              else return 0;
    } // ends class ResultData

  • TreeSet vs Collection.Sort / Array.sort for Strings

    Gurus
    I am pondering weather to use TreeSet vs the Collections.sort / Array.sort for sorting Strings.
    Basically I have a list of Strings, i need to perform the following operations on these Strings
    1) Able to list Strings starting with a Prefix
    2) Able to list Strings Lexically greater than a String
    Any help would be greatly appreciated!
    Thanks a bunch

    SpaceShuttle wrote:
    Gurus
    I am pondering weather to use TreeSet vs the Collections.sort / Array.sort for sorting Strings.
    Basically I have a list of Strings, i need to perform the following operations on these Strings
    1) Able to list Strings starting with a Prefix
    2) Able to list Strings Lexically greater than a String
    Any help would be greatly appreciated!
    Thanks a bunchBig-O wise, there's no difference between sorting a list of N elements or inserting them one by one in a tree-set. Both take O(n*log(n)). But both collections are not well suited for looking up string that start with a certain substring. In that case you had better use a Patricia tree (or Radix tree).
    Good luck.

  • Can you help with RoboHelp Version 11: WebHelp Index Keyword Sorting?

    I'm new to RoboHelp 11, and I am finding it difficult to alphabetize topics listed under my Index Keywords. When I look at the keyword topics in my RoboHelp HTML editor, they are listed in alphabetical order (see the Tools topic in the first image), but when I generate WebHelp the Tools topics are not in the correct order (second image). I believe that the problem pertains to new entries made to a converted RoboHelp Version 6 WebHelp application. Basically, I have been adding content to several old version 6-generated html files in the new RoboHelp HTML editor.
    Another issue that's perplexing is the fact that the Move Up and Move Down icons at the top of the Index editor pod, or whatever it's called, are grayed-out (not functioning). I remember with the Version 6 application, they worked fine.
    Can anyone offer any suggestions on how to get the index alphabetized? I appreciate your help.

    Hi, pweb248
    Just an expansion of what Rick has suggested. Binary index is only used when Microsoft HTML Help "CHM" is your primary layout. So, because WebHelp is your primary layout, Binary should definitely be unchecked. Selecting the Index file (HHK) is fairly standard for WebHelp use and it is sorted numerically and alphabetically by default. The HHK file contains all the Index keywords and their topic associations all tucked into one file, whereas adding Index Keywords using the "Topic" radio button embeds the coded reference right in the topic html file itself.
    This online help topic explains a little more about the Sorting options depending on the primary layouts and whether Binary is selected.
    Adobe RoboHelp 11 * Edit index keywords
    This is the key paragraph:
    >>Note: The Sort command is unavailable with a binary index. The sort function is enabled only when the primary layout is HTML Help and the Index is set to Index File with no Binary Index. In all other layouts, the index remains sorted but for HTML output, the sorting of the index can be changed. Sorting enables the up and down keys on Index Pod.<<
    As you have noticed, your Index Designer view is apparently working as documented. I share your puzzlement about the out-of-sort listing in the WebHelp output shown in your screenshot. I wonder if there is some left-over crud from the ancient RoboHelp 6 code that is not converted properly and gumming up the works? Also curious if you have more than one Index in your project and if you are selecting the right one in the WebHelp Settings > Content dialog. Maybe Rick, Peter or Willam can shed some light on this?
    John

  • I need sorting VI that returns the sorted array element's positions in the unsorted array

    I need a VI that will very quickly (n log n) sort a 1D array of doubles.  This VI should not only output the sorted array, but for each of the sorted array elements, it should also output that sorted array element's position in the unsorted array.  So for example if the input array were:
    unsorted_array
    4.1
    2.3
    7.0
    5.6
    10.2
    Then the output arrays would be:
    sorted_array
    2.3
    4.1
    5.6
    7.0
    10.2
    indices_array
    1 (the value 2.3 is located at position 1 in the unsorted_array)
    0 (the value 4.1 is located at position 0 in the unsorted_array)
    3 (the value 5.6 is located at position 3 in the unsorted_array)
    2 (the value 7.0 is located at position 2 in the unsorted_array)
    4 (the value 10.2 is located at position 4 in the unsorted_array)
    This way I could generate the sorted_array using just the indices_array and the unsorted_array.  Has anyone written a nifty piece of code to do this?  I did some research on (n log n) sorting algorithms but most of them use recursion which I don't know how to do in LabVIEW.  It would also be nice to have an algorithm like this that could sort an array of strings.
    cheers,
    Richard

    Try something like the attached example (LabVIEW 7.0). I think it does what you need.
    (To understand the code, it is important to know that arrays of clusters are sorted by the first element in the cluster).
    Sort array itself sorts also array of strings, so you could just substitute, keeping the rest of the code the same.
    Sort array uses a variation of quicksort, so it should have about NlogN complexity.
    (If you think you only need the array of indices to later generate the sorted array, it does not make much sense to even do it. To get the indices, you need to sort the array anyway. You should just sort the plain array directly.
    Message Edited by altenbach on 07-13-2005 03:47 PM
    LabVIEW Champion . Do more with less code and in less time .
    Attachments:
    SortAndIndex.vi ‏26 KB

  • Sorting array list

    can u please give me the source code for:
    sorting array list for ascending and descending order

    You already have the source code.

  • Sorting array vs sorting paginated array

    ...pulling in a long list of photos in a gallery, and I have
    a sort function working within the pages of data fine. I need to
    bring it back out of the paging stuff so that it sorts the data,
    THEN passes to the paging function.
    My data comes from mysql > php > xml > Flex into an
    ArrayCollection, referred to in MXML as {acSlides}.
    Pass the array collection to the paging system like:
    <utils:FXCPager id="fxcPager" pageIndex="{currentPage}"
    pageSize="{pageSize}" dataProvider="{acSlides}" />
    then assign in repeater:
    <mx:Repeater id="slideRepeater"
    dataProvider="{fxcPager.pageData}">...</>
    There is a button for sorting that calls a function a la:
    private function sortByRating():void {
    var sort:Sort = new Sort();
    sort.fields = [new SortField("rating",false,true)];
    fxcPager.pageData.sort = sort;
    toggleRating = false;
    fxcPager.pageData.refresh();
    What do I need to do to get this sort function to work on the
    {acSlides} array collection instead of {fxcPager.pageData} ???
    Thanks!

    OK I have resolved the error by importing the class adGroup. However now I am back to the original problem which is how to sort the DisplayName alphabetically and keep the associated link in tact. I created the class to avoid sorting parellel arrays but I am afraid it solved nothing as I have no idea how to sort the class. I tried just sorting it like an array:
      Arrays.sort(bAD.getGroups()but receive the following error:
    java.lang.ClassCastException: com.mylbean.adGroup incompatible with java.lang.Comparable
    at java.util.Arrays.mergeSort(Arrays.java:1160)
    at java.util.Arrays.sort(Arrays.java:1131)
    >
    I would assume this message is caused because I cannot sort a class array using this method. But being newer to Java I really have no idea how to get the class to sort by DisplayName before displaying to the user.
    So at this point the code works fine but how do I display alphabetically? All suggestions are appreciated.

  • Current index to an Array

    I don't know how to get the current index to an array. I wrote a temp vi (attached file) to show my problem. Eventually the output of the array will go to the serial port.
    Attachments:
    temp.vi ‏13 KB

    Schmir1,
    In your program you have a 0 wired to the index array terminal and so you are always displaying the element at index 0. When you change increment or decrement the array index you are only changing the display on the frontpanel, the entire array is still present there and so it will still display the index 0 element.
    As I understand from your program you are trying to pass individual hex values to the serial port. You will have to wire different values to the index terminal of the index array function during each run to pass individual value.
    I modified your application for easier understanding.
    Hope this helps,
    Pravin
    Attachments:
    temp[1].vi ‏15 KB

  • CompareTo and Sorting Arrays

    I am trying to sort an array of telephone directory information by last, first names, but am having trouble understanding how to use the compareTo method to do so. I thought I could use Arrays.sort, but this doesn't seem to work....any help would be appreciated.
    public static Person [] sort(Person [] people) {
    Person [] sorted = Arrays.sort(people);
    return (Person[])sorted.toArray(new Person[sorted.size()]);
    }/* end sort method */
    //From Person class
    public int compareTo(Object o) {
    Person p = (Person)o;
    int temp;
    if((temp=getLastName().compareTo(p.getLastName())) == 0)
    if((temp=getFirstName().compareTo(p.getFirstName())) == 0)
    //not sure what to do here
    return temp;
    }

    You want to return a negative or positive or zero integer if this item is less than, greater than, or the same as, the object passed as an argument, right? (Read the API.)
    You're trying to sort by last name first, and if they're the same, then the first name, right?
    So you're not really checking for zero, you're checking for non-zero.
    I'm assuming that first name and last name are given by strings, which implements Comparable. So you can do:
    public int compareTo(Object o) {
      Person p = (Person)o;
      int temp = getLastName().compareTo(p.getLastName());
      if (temp != 0)
        return temp;
      // implicit else here
      // MORE CODE GOES HERE
    }I'll let you do the "MORE CODE GOES HERE" as an exercise.
    BTW if you're implementing Comparable, you should probably be overriding equals() as well.

Maybe you are looking for

  • HP LP2275w Monitor HDMI to DisplayPort possible?

    Hello forum,  In the proccess of connecting my monitor HP LP2275w to computer HP Pavillion. The computer has HDMI and VGA output, the monitor has DVI and DisplayPort inputs. Recently bought a HDMI to DisplayPort adapter, in order to use the HDMI-cord

  • Premiere Pro - Creating Menu After Effects & Encore

    I will admit right off the bat that I am a new user to the Adobe Video Editing product line and that will be obvious with the following question.  I have been doing some video editing in Premiere Pro CS5 with success (great product)!  Now, here is wh

  • Have just updated to iBook Author 1.01 and have lost my icons

    Have just updated to iBook Author 1.01 and have lost my icons in the left hand column, which show each page of the book. They are now all blank white icons instead of miniature images of the larger pages. Also have lost some images within the pages o

  • Loaction of Supposed FIles on Solaris Companion CD

    I read an article about having a KDE desktop on a Solaris system. The article said everything I need is on the Solaris 10 Companion CD. So, as naive as I am, I went through the requirement list: SFWgcm SFWgcc2l SFWqt SFWsdl SFWgdb SFWoggl SFWlibsane

  • Multiple IMAP Path Prefixes in Mail

    Is there any way I can put mutiple IMAP Path Prefixes under Accounts in Mail? Furthermore there is a pulldown under my INBOX full of mailboxes that are already deleted on the server... when I select delete there is a popup that says they're already d