Sorting array of numbers

I have an multiple arrays of numbers 1-10 in different orders. I want to sort them in ascending order.
example
for(int pass=0; pass < sizeofarray; pass++){
    for(int t=0; t < sizeofarray; t++){
        if(array[t] > array[t+1]){
            hold=array[t];
            array[t] = array[t+1];
            array[t+1] = hold;
}This loops through 10 times no matter how the array is originally sorted. How do I decrease the number of times this cycles if the array is pre-sorted?
example arrays {10,9,8,7,6,5,4,3,2,1} need to go 10 times
{1,2,3,4,5,6,7,8,9,10} only needs to check it once.
Help, please only loops, no array.sort. This is a homework assignment.

Quicksort while effective, is not what I needed. A modified bubble sort is what I wanted. Thanks to all who posted. I found the logic I was able to modify for my needs at
http://www.autoobjects.com/Home/Teaching/CmpE_126/CmpE_126_Lectures/Sortings/sortings.html#Bubble_Sort
here's basically what it did (in C++):
    Improved Bubble Sort                                                                                                        */
void BubbleSort( UserData x[ ], int siz ){
        int i, j, switched;
        /* outer loop controls the number of pass */
        for( i = 0, switched = true; i < siz - 1 && switched == true; i++ ){
                /* initially no interchanges have been made on this pass */
                /* inner loop controls each individual pass */
                for( j = siz - 1, switched = false; j > i; j-- ){
                        if( getKey( x[ j ] ) > getKey( x[ j - 1 ] )){  /* an interchange becomes required */
                                switched = true;
                                Swap( x[ j ], x[ j - 1 ] );
                        }        /* inner loop */
                }       /* outer loop */
        return;
        }Thanks to jbish who had the most useful answer for my needs.

Similar Messages

  • Sorting an array of numbers with loops

    Hi, i'm looking for a way to sort an array or numbers with loops.
    my array looks like this. int[] numbers = {5,2,7,9,1}
    i know how to use the "sort" method and i want to do it without the sort method, but i am not very clear on the logic behind it.
    by the end it should look like this, {1,2,5,7,9}
    i know 2 loops are used, can you please give me a logic to work with.
    i have started the loops but what to do inside???
    int temp;
    for (int i=0; i<numbers.length; i++){
    for (int j=1; j<numbers; j++){
    if (numbers<numbers[j])
    temp = numbers[i];
    Any suggestions i will be thankful for.
    thank you.

    fly wrote:
    no not really a homework question.. i want to improve my logic because it is very poor at the moment.. but i'm sure someone knows how to sort an array with loops only.Yes, we do know how to do it, I once wrote a heapsort in assembly code, as a real work project. But you rarely get a project like that the good ones were all done years ago.
    All the algorithms I suggested you look at use loops. the simplest and slowest is the bubble sort. This one runs by comparing values and swapping their locations, the wikipedia article http://en.wikipedia.org/wiki/Bubble_sort has the algorithm.

  • Using .sort() to sort an array of numbers NOT as strings

    Hi,
    is there a function or simple way to sort an array of numbers in order of their values and not as strings? E.g, have 100 come AFTER 9; (9, 100) not (100, 9).
    Thanks.

    use the ARRAY.numeric parameter.
    (and you can always use a custom sort function parameter for more customized sorts.)

  • Sort array

    Hello to all,
    I would like to ask you a question.
    I need to sort an array of numbers and strings.
    Can I sort the array by name?

    I'm sorry, I explained I was wrong or inaccurate.
    I enclose the table (array) I want to reorder.
    Assuming that the column "Tratta" may have also different elements (not just Piacenza - Parma), I would be able to sort the table by clicking one of the elements of the columns (for example: sort the table by "Tratta" or by "Km", etc )
    Attachments:
    Tab.png ‏141 KB

  • PHP-sort arrays by key

    very OT, I hope I'm not abusing this forum... If someone can
    help, great!
    Say I have a large array, called $orders, looking like this:
    Array
    [retail_2833200] => Array
    [0] => bobby
    [1] => 29 Jan 2007 - 10:54
    [2] => 212-879-6786
    [retail_2833231] => Array
    [0] => john
    [1] => 29 Jan 2007 - 11:04
    [2] => 718-768-7685
    etc......
    Now I want to be able to sort the array, by any key (i.e. by
    name, date, or phone number).
    I have done that before, but I'm sure my method is not the
    best method to do that.
    Here's how I do it:
    foreach($orders as $order){ // I append the name value to the
    array keys (and insert a separator #)
    $sort_by_name[] = $order[0].'#'.$order;
    natcasesort($sort_by_name); // I sort the resulting new array
    (hence sorting them by name)
    foreach($sort_by_name as $sort){ // I remove the appended
    names, to get back to original values
    $final_array[] = preg_replace('/.*?#/','',$sort);
    now I have a new array called $final_array, sorted by names.
    I'm sure there is a better way to do this!!!!
    seb ( [email protected])
    http://webtrans1.com | high-end web
    design
    Downloads: Slide Show, Directory Browser, Mailing List

    Michael Fesser wrote:
    > .oO((_seb_))
    >
    >> Say I have a large array, called $orders, looking
    like this:
    >> [...]
    >>
    >> Now I want to be able to sort the array, by any key
    (i.e. by name, date, or phone number).
    >
    > Use your own comparison function, given as a callback to
    uasort().
    >
    >
    http://www.php.net/uasort
    >
    > To be flexible you could use a global variable (or a
    class member if
    > you'd do it in OOP), so the comparison function knows
    which key you want
    > to use for sorting, e.g.
    >
    > $col = 2;
    > $asc = 1; // -1 for descending order
    >
    > function cmpOrders($a, $b) {
    > global $col, $asc;
    > return strnatcasecmp($a[$col], $b[$col])*$asc;
    > }
    >
    > uasort($orders, 'cmpOrders');
    >
    > This would sort by phone numbers, with $col = 0 it would
    sort by name.
    > It could also be extended to use numeric comparison
    instead of string
    > comparison when necessary.
    >
    > The only problem so far are the dates. It would really
    help if they
    > would be stored as "YYYY-MM-DD hh:mm" or at least as
    Unix timestamps.
    > The format they are currently stored in can't be used
    for sorting.
    >
    > Micha
    perfect, this works, thanks a lot Micha. I did stumble upon
    uasort, looking in php.net manual but
    did not understand how to use it...
    Yeah I'll have to reformat the date, no problem.
    seb ( [email protected])
    http://webtrans1.com | high-end web
    design
    Downloads: Slide Show, Directory Browser, Mailing List

  • 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?

  • Need help with ouput of a list or array of numbers input from user

    I'm only a few weeks into learning java, so this may seem simple to some, but...
    I am trying to write a program that will receive numbers from a user,
    and then list, add, average those numbers. I've got the program to
    work except for listing the numbers that were input.
    Can someone help guide me????
    i've left the code I've tried in as comments.
    Enter an integer value, the program exits if the input is 0:
    20
    Enter an integer value, the program exits if the input is 0:
    40
    Enter an integer value, the program exits if the input is 0:
    60
    Enter an integer value, the program exits if the input is 0:
    80
    Enter an integer value, the program exits if the input is 0:
    0
    Total numbers entered: 4
    The array of numbers is: 0 0 0 0
    The sum is 200
    The average is 50
    The maximum number is 0
    The minimum is 0
    Here is my code:
    * Title:        Reads integers and finds the total, average, maximum of the input values
    * Description:
    * Copyright:    Copyright (c) 2002
    * Company:      Duke Court.
    * @author Mary Davenport
    * @version 1.0
    public class part3page6
      public static void main(String[] args)
      int data = 0;
      int sum = 0;
      int countnum = -1;
      int maximum = 0;
      int minimum = 0;
      int average = (countnum - 1);
      do
          System.out.println("Enter an integer value, " +
            " the program exits if the input is 0:  ");
          data = MyInput.readInt();
          sum += data;
          countnum++;
        } while (data != 0);
          //in order to figure the max & the min it appears that the
        //program will need to utilize arrays to store the individual numbers
        //that are input from the user.
        //create an array of the input data
        int[] number = new int[countnum];
        //creat a list of the input data
        int []myList = {data};
        //lists how many numbers entered
        System.out.println("Total numbers entered:  " + number.length);
        //list array of numbers -- this is giving me [I@3179c3,
        //instead of 20, 40, 60, 80 when I use "new int[countnum]"
    //     System.out.print("The array of numbers is: "
    //      + new int[countnum]);
        //list array of numbers:  this is giving me " 0 0 0 0 "
           //instead of 20, 40, 60, 80  with the following for statement
           // (number[i] + " ")
        System.out.print("The array of numbers is: ");
          for(int i=0; i<number.length; i++)
            System.out.print(number[i] + "  ");
      //list mylist of numbers from input, 20, 40, 60, 80
      //output is The list of numbers is: [I@3179c3
    //  System.out.print("The list of numbers is: " + myList);
        System.out.println();
        System.out.println("The sum is " +  sum);
        average = sum/countnum;
        System.out.println("The average is " + average);
        System.out.println("The maximum number is " +  maximum);
        System.out.println("The minimum is " +  minimum);

    When you input the data you need to save it to the array. Currently you are not saving the value you are just adding it
    ArrayList nums = new ArrayList();
       do
           System.out.println("Enter an integer value, " +
             " the program exits if the input is 0:  ");
           data = MyInput.readInt();
    nums.add(new Integer(data));
           sum += data;
           countnum++;
         } while (data != 0);

  • How do I convert a 1-D array of cluster of 5 elements into a 2-D array of numbers? (history data from a chart)

    Hello,
    in my vi I have a chart with 5 Plots displaying measurement data.
    The user should be able to save all the history data from the chart at anytime. (e.g. the user watches the chart and some event happens, then he presses a "save"-button)
    I know, that I can read out the history data with a property node. That is not the problem. The problem is, how do I handle the data? The type of the history data is a 1-D array of cluster of 5 elements.
    I have to convert that data somehow into a 2 D-array of numbers or strings, so that I can easily save it in a text-file.
    How do I convert a 1-D array of cluster of 5 elements into a 2-D array of numbers?
    I use LabVIEW 7.1
    Johannes
    Greetings Johannes
    Using LabVIEW 7.1 and 2009 recently
    Solved!
    Go to Solution.

    Gerd,
    thank you for the quick response and the easy solution.
    Look what I did in the meantime. I solved the problem too, but muuuch more complicate :-)
    And I have converted the numbers to strings, so that I can easily write them into a spreasheet file.
    Johannes
    Message Edited by johanneshoer on 04-28-2009 10:39 AM
    Greetings Johannes
    Using LabVIEW 7.1 and 2009 recently
    Attachments:
    SaveChartHistory.JPG ‏57 KB
    SaveChartHistory.JPG ‏57 KB

  • How to create a list/array off numbers with boolean attributes

    Hi,
         Maybe the title doesn't explain this too well but what I'm trying to do I'd imagine should be straight forward, I just don't know how!
    I want an array of numbers to be entered by a user, and for each of these numbers I wish to have a boolean, (it will select later what action is performed on that number)
    The array size can vary
    e.g.
    element       Numeric Value              Boolean
    0                       5                             True
    1                       20                           True
    2                       -5                            False
    3                       10                           True
    n                       100                         False
    I don't see any list with numeric and boolean, maybe I just haven't spotted it or do I have to make it somehow?
    Any suggestions please?
    Thanks!
     p.s. if anyone else is using Opera Browser to post here, hitting enter work properly for ye when entering text? For me it causes the cursor to go up one line instead of down! Drives me nuts! It only happens with this NI forum
    Solved!
    Go to Solution.

    Hi thanks for the reply, 
                              It not really what I'm looking for though. 
    I require is a control that inputs both numeric and boolean,  as in the example I mentioned. I guess I'm looking for a cluster really but I thought there may be something more straight forward.
    From the example I gave  
    Element 0 of this array has been entered as a x, and the boolean True was entered (so I perform a "test" A on value x)
    Element 1 of this array has been entered as a y, and the boolean True was entered (so I perform a "test" A on value y)
    Element 2 of this array has been entered as a z, and the boolean False was entered (so I perform a "test" B on value z)
    I could also use a 2d array were I enter another numeric value (0/1 for False/True) but I'm not sure I can limit this column only to accept 0 or zero and the first row any number.
    I was hoping there would be some easier way to do this

  • Fastest way to format an array of numbers

    I am collecting 2D array of DBLs to be later processed by other Vis.
      The process worked fine when I saved the array to a file (standard %.3f, write to spreadsheet) formatting, then later have a separate VI to open the file and process it.
    The same process did not work when I tried to process the 2D array on the fly, without saving/opening to file.
      After debugging, I found out what was holding me back. Yep you guessed it, the formatting. Without save to spreadsheet, instead of “0.000”, the value is not 2.803E-42 (I need to to be 0.000). What is the most efficient way to format the numbers to “.3f”,  on the fly (without saving to file)?
    Best,
      Santiago

    .3f is the same as a precision of 3 input to the number to fractional string vi (which can handle arrays automatically)
     To keep only a precision of 3 you can also do it numerically by multiplying by 1000, rounding then dividing by 1000. 
    Here is a screenshot of the code using the two different methods. The numeric method should be fastest.
    Systems Test Engineer
    Certified LabVIEW Architect (CLA)
    Attachments:
    format array of numbers.png ‏4 KB

  • Finding Mode of an array of numbers.

    I'm having troubles with finding the mode of an array of numbers.
    When the mode is in the middle of the set of numbers, it works, but when it is at the end, it doesnt.
    For example..
    if i had the numbers ...
    2,3,3,4,5,6,6,6 in an array, it would tell me that the mode is 3.
    if i had the numbers...
    2,4,5,5,5,6 in an array, it would tell me that the mode is 5.
    So the first set of numbers, the mode is incorrect, but the second set of numbers is correct.
    The following is my code...
    public static int getMode(int[] list)
    int mode = 0;
    int elements = 0;
    int tempMode = list[0];
    int temp = 1;
    for(int x = 1; x < list.length; x++)
    if(list[x-1] == list[x])
    temp++;
    }else{
    if(temp > elements)
    System.out.println("entered");
    tempMode = list[x-1];
    elements = temp;
    temp = 1;
    }else{
    temp = 1;
    mode = tempMode;
    return mode;
    }

    You need to add another test at the end of the loop:
        public static int getMode(int[] list)
            int mode = 0;
            int elements = 0;
            int tempMode = list[0];
            int temp = 1;
            int x;
            for (x = 1; x < list.length; x++)
                if (list[x - 1] == list[x])
                    temp++;
                else
                    if (temp > elements)
                        tempMode = list[x - 1];
                        elements = temp;
                        temp = 1;
                    else
                        temp = 1;
            if (temp > elements)
                tempMode = list[x - 1];
            mode = tempMode;
            return mode;

  • 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.

  • OCR - array of numbers

    Hello
    I am beginner in image processing and I  need sugestion how to create array of numbers from image.
    So far I ve processed this:
    to that:
    in vision builder.
    Now I should divide this square into 9x9 smaller and then run OCR in each of them?
    And what about size of the base numbers in OCR, should I create instances of the same number (depending on size?)
    Thanks for help

    I ve done that in 6 steps starting from:
    1) color plane extraction HSL
    2)Local Threashold Background Correction  look for dark objects 11x11
    3)Binary image conversion
    4)Adv Morphology remove border objecst
    5)Lookup table Equalize and 4x find straight edge
    but sometimes after morphology i get that:
    depending on foto quality
    thanks for some suggestions

Maybe you are looking for