Sorting an array of integers into ascending order

Today I decided to blow the cobwebs off my old laptop and see what I could remember from my Java days.
As a task for myself to see what I could remember, I decided to try and write a program that does the following:
- Declares an array of 4 integers
- Sorts the array into ascending order, from lowest to highest.
- Prints on screen the sorted array.
After an hour or so I finally cracked it, and ended up with a working program. Here she is:
public class Sorting_arrays_1
    public static void main()
       int [] array = {4,3,7,1};
       //A variable used to help with swopping values
       int temporary;
          //finds the smallest number out of elements 0, 1, 2, and 3 of the array, then moves it to position 0
          for (int count = 0; count<array.length;count++)
            int smallestNumber = array[0];
            if (array[count] < smallestNumber)
                smallestNumber = array[count];
                temporary = array[0];
                array[0]=array[count];
                array[count]=temporary;
         //finds the smallest number out of elements 1, 2, and 3 of the array, then moves it to position 1
         for (int count = 1; count<array.length;count++)
            int smallestNumber = array[1];
            if (array[count] < smallestNumber)
                smallestNumber = array[count];
                temporary = array[1];
                array[1]=array[count];
                array[count]=temporary;        
          //finds the smallest number out of elements 2 and 3 of the array, then moves it to position 2
          for (int count = 2; count<array.length;count++)
            int smallestNumber=array[2];
            if (array[count] < smallestNumber)
                smallestNumber = array[count];
                temporary = array[2];
                array[2]=array[count];
                array[count]=temporary;     
         //prints the array in ascending order
         for (int count=0; count<array.length;count++)
             System.out.print(array[count] + " ");
}Could this code be simplified though? Maybe with a for loop?
I mean, it does the job, but it looks so clumbsy and inefficient... Imagine how much code I would need if I wanted to sort 1000 numbers..

Use bubble sort if u want a quick fix
public static void bubbleSort(int [] a)
for(int i=0; i<a.length-1; i++)
     for(int j=0; j<a.length-1-i; j++)
          if(a[j]>a[j+1])
               int temp = a[j];
               a[j]=a[j+1];
               a[j+1]=temp;
Or use Merge sort if u want better run time... ie.(N log N)

Similar Messages

  • Write an algorithm to sort an array of integers

    "Write an algorithm to sort an array of integers"
    I was asked this at an interview and required to do it in 5 mins. I don't think you can use sort them by putting them in a collection, i think you need to write an algorithm from scartch. Any idea what the best way to do this would have been?

    Depends what you mean by "best."
    BubbleSort is probably the only one I could write off the top of my head in five minutes, but as sorting routines go for practical use, it sucks. If you know how to write MergeSort or QuickSort or dman near anything off off the top of your head, that would proabably be better.
    No one sorting algorithm is "best" without any context, however.
    If you don't know any sorting algorithms, use google or your data structures and algorithms textbook.

  • Arranging 3 integers in ascending order

    i need the code for arranging 3 numbers in ascending order. the numbers will be typed in a input dialog box. someone please help! it's homework for tomorrow dec 16 2005.

    naw, its cool. do you know any web pages where i
    might could find the code?
    e359. Sorting an Array
    It's an extremely important skill to learn how to search the web. Not only will it increase your research and development talents, it will also save you from asking questions that have already been answered numerous times before. By doing a little research before you ask a question, you'll show that you're willing to work and learn without needing to have your hand held the entire time; a quality that is seemingly rare but much appreciated by the volunteers who are willing to help you.
    If you've done the research, found nothing useful, and decide to post your question, it's a great idea to tell us that you've already searched (and what methodologies you used to do your research). That way, we don't refer you back to something you've already seen.

  • How to convert an array of Integers into String

    So how can an array of integers be converted into a string?
    As I do not have a javac with me now, I hope you guys could help.
    Can it be done this way:
    int [] value = new int[] {2,3,4,5,6,7}
    String strValue = "";
    for (i=0; i<value.length-1; i++)
    strValue += value;

    Instead of working with Strings, I would suggest you use a StringBuffer. It will improve memory utilization.
    Like this:
    int [] values = new int[] {2,3,4,5,6,7};
    StringBuffer sbTmp = new StringBuffer();
    final int size = values.length;
    for (i = 0; i < size; i++) {
    String intStr = Integer.toString(values);
    sbTmp.append(intStr);
    String strValues = sbTmp.toString();

  • Is there a VI to turn a 1-D array of integers into Intel Hex Format string?

    I have a 1-D array of 16-bit integers.  I guess I can turn these numbers into 2x8 bit numbers.  After that I would like to convert this arary of numbers into an Intel Hex format string.  Is there a VI for this?

    you can simply typecast your integer array as a string and it will be in the "Intel" or Little Endian format
    you can pass the array through the swap bytes vi to format the string in "Motorolla" or Big Endian format
    - James
    Using LV 2012 on Windows 7 64 bit
    Attachments:
    U16_to_String.vi ‏8 KB

  • What do i use to order numbers in ascending order???

    anybody? i need to set 6 numbers into ascending order.

    java.util.Arrays.sort()
    java.util.Collections.sort()
    The Java� Tutorial - Object Ordering
    Making Java Objects Comparable
    ~

  • Sorting a vector in ascending order

    Hi
    I hava a vector that consists of integers.
    How can I code it in java so that the vectors is sorted in ascending order.
    thanks

    try this
    Object []obArr=urVector.toArray();//urVector is your Vector of Integers
    Arrays.sort(obArr);
    Regards,
    AryaSP.

  • Arrange Array in ascending order by date

    Kindly help me sort out the order by problem.
    I have a date array which goes like;
    12/3/2012
    11/3/2012
    12/5/2012
    12/8/2012
    12/6/2012
    12/12/2012
    12/10/2012
    12/17/2012
    I need to arrange it in ascending order, like
    11/3/2012
    12/3/2012
    12/5/2012
    12/6/2012
    12/8/2012
    12/10/2012
    12/12/2012
    12/17/2012
    Please help.
    Thank you in advance.
    Regards
    Grugh Mike
    Success is Everything !!

    Grugh_Mike wrote:
    is'nt there any easier method to sort a time array ?
    It's a lot easier than trying to manipulate the strring into yyyy/dd/mm format and sorting alphabetically.
    Bill
    (Mid-Level minion.)
    My support system ensures that I don't look totally incompetent.
    Proud to say that I've progressed beyond knowing just enough to be dangerous. I now know enough to know that I have no clue about anything at all.

  • How to sort  the arry value in ascending order

    I have a string array where i need to sort the below values in ascending order in the same format...can anyone give me clue on this?
    9.3
    3.1
    9.1
    19.1
    19
    9.4
    9.1.1
    the sorted order should be
    3.1
    9.1
    9.1.1
    9.3
    9.4
    19
    19.1

    You may have easier luck writing your own comparator for this. These are headings in a table of contents, right?
    Write a comparator that tokenizes a string on the '.' character, or use a StringBuffer to remove them, and then order the elements according to the combined numbers. Since alphanumeric would order this list as you want it anyway you could just order that way once the '.' are removed.
    In other words your comparator would do this in the "compare" method:
    public class MyComparator implements Comparator, java.io.Serializable {
    private static Comparator stringComparator = java.text.Collator.getInstance();
    ...constructor(s), your own private "instance" variable of type MyComparator, a getInstance() method of your own, yadda yadda...
    public int compare(Object item1, Object item2) {
    try {
    value1 = removePeriods((String)item1);
    value2 = removePeriods((String)item2);
    if (value1 == null) {
    return (value2 == null) ? 0 : (-1);
    return compare(value1, value2);
    } catch (ClassCastException cce) {
    System.err.println("Wrong Object Type, JackAss!");
    protected int compare(String str1, String str2) {
    return MyComparator.stringComparator.compare(str1, str2);
    private String removePeriods(String value) {
    StringBuffer sb = new StringBuffer(value);
    int decimalIndex = value.indexOf('.');
    while (decimalIndex != -1) {
    sb.delete(decimalIndex, (decimalIndex + 1));
    }

  • How To: Sort Numbers in Ascending Order in a Generated List

    Greetings! How do I set up a Generated List of Paragraphs so that it sorts in true ascending order? What I want is:
    1.1
    1.2
    1.3
    1.4
    1.5
    1.6
    1.7
    1.8
    1.9
    1.10
    I have tried every trick I can think of with the sort order listed on the reference page. But all I can get is something that sorts by individual number (ignoring the numeric value) like:
    1.1
    1.10
    1.11
    1.2
    1.20
    1.21
    1.3
    Any help is much appreciated!

    Hello there, Michael! Thanks so much for looking at my post! Alas, the LOP will not work. I should have explained more, but it was so complicated I thought folks would give up reading.
    Here's the best I can render it without getting permission to share a good example document. I do not blame anyone if it's too cumbersome or convoluted to wade through...
    This is a requirements document which has sort of a "legal" tinge to it--as the document evolves we must maintain traceability for individual requirements. This means, for example:
    Version 1 - I have requirements 1 and 2.
    Version 2 - I need to add a new requirement, which should appear before requirement 1 in the document. Even though it comes before requirement 1 in the document, numerically it will be requirement 3 and requirement 1 will remain requirement 1.
    Version 3 - I need to remove requirement 2. Even though I now have only 2 requirements, their numbers will not change (they remain requirements 1 and 3, appearing in reverse order).
    Version 4 - I need to move requirement 3 to be after requirement 1. Again, the requirements keep their original number, even though their position has changed and there is no longer a "requirement 2" number in use.
    Originally, I told the team (I'm doing this for a different dept), that they would have to hand-number requirements, which they did for a while. But that was getting very cumbersome, and the scenarios above are limited to one or two occurrences per document. So I created an auto-number sequence for them to use in the initial version and added a little smoke-and-mirrors work process to take care of changes in later versions. The last bit of chicanery I cannot get to work is the index...
    Even if there are no changes to the requirements after the initial version, the index still does not sort in ascending numeric order. It was working with the hand-numbered requirements because they were using leading zeros. But without being able to include leading zeros in the auto-numbering formats (I tried the "use a zero as a tab leader" solution and like to have thrown my new monitor out of the window), I cannot find a solution.
    Or rather, I think the solution is "you have to hand-number requirements".
    For anyone who has made it this far, I truly appreciate your time and patience!
    SFT

  • I want to create an array that goes into a case structure where each element in the array is an individual case and gets done in order

    I want to create an array that goes into a case structure where each element in the array is an individual case and gets done in order. Any ideas, I've been playing with the idea but have had no luck, is this even possible?

    Hi,
    Please check it out the attached Vi.. Is this you need?
    Sasi.
    Certified LabVIEW Associate Developer
    If you can DREAM it, You can DO it - Walt Disney
    Attachments:
    Event.vi ‏11 KB

  • Apple TV sorts my photos only in ascending order, how can I change so the most recent EVENTS appear first?

    Apple TV sorts my photos only in ascending order, how can I change so the most recent EVENTS appear first?

    I'm looking for an answer to this, too, since I have thousands of Events, and so scrolling down to the bottom every time I want to show my newest photos makes it almost unusable.

  • Is it possible to sort Mac Mail Rules into alphabetical order?  I have in excess of 50 rules and everytime I want to add to a rule, such as "delete incoming" I have to go through the entire list to find it.

    Is it possible to sort Mac Mail Rules into alphabetical order?  I have in excess of 50 rules and everytime I want to add or amend a rule, such as "delete incoming" I have to go through the entire list to find it.  I have tried clicking on the heading "Description" but it does not sort.  Any assistance would be greatly appreciated

    Hi,
    According to your description, my understanding is that use CMAK to configure split tunneling on VPN clients, traffic to specified devices can be routed via their own default gateway.
    If the manually added route entries all have default metric and interface, clients will select one by the default routing rule, can’t select one of them according to clients’ own conditions. So, I am afraid that CMAK can’t implement the function which you need.
    A blog described about How to configure split tunneling on VPN clients using CMAK, for your reference:
    http://blogs.technet.com/b/rrasblog/archive/2007/06/11/split-tunnelling-using-cmak.aspx
    Best Regards,
    Eve Wang 
    Please remember to mark the replies as answers if they help and unmark them if they provide no help. If you have feedback for TechNet Support, contact [email protected]

  • How do you sort into descending order?

    How do you put your data into a descending/ascending order?

    This is one way (click the disclosure triangle by the column letter to get this contextual menu):
    SG

  • Verifier Error: Exception handlers not sorted in ascending order by the off

    Hello,
    Java Card 2.2 did not convert my Applet !
    Java Card 2.2.1 & 2.1.2 do not report this Error and the Applet is working !
    What's wrong here ?
    D:\save\smsTest>C:\Programme\Java\jdk1.5.0_06\bin\java -classpath D:\java_card_kit-2_2\lib\converter.jar;D:\java_card_kit-2_2\lib\offcardverifier.jar com.sun.javacard.converter.Converter -config SMS_JCDK_2_2.opt
    Java Card 2.2 Class File Converter (version 1.3)
    Copyright 2002 Sun Microsystems, Inc. All rights reserved. Use is subject to license terms.
    warning: You did not supply export file for the previous minor version of the package
    parsing D:\save\smsTest\com\gieseckedevrient\jctt\smsTest\IExceptionConstants.class
    parsing D:\save\smsTest\com\gieseckedevrient\jctt\smsTest\ITestConsts.class
    parsing D:\save\smsTest\com\gieseckedevrient\jctt\smsTest\InfoData.class
    parsing D:\save\smsTest\com\gieseckedevrient\jctt\smsTest\SMS.class
    parsing D:\save\smsTest\com\gieseckedevrient\jctt\smsTest\StringConsts.class
    converting com.gieseckedevrient.jctt.smsTest.IExceptionConstants
    converting com.gieseckedevrient.jctt.smsTest.ITestConsts
    converting com.gieseckedevrient.jctt.smsTest.InfoData
    parsing D:\java_card_kit-2_2\api_export_files\java\lang\javacard\lang.exp
    converting com.gieseckedevrient.jctt.smsTest.SMS
    parsing D:\java_card_kit-2_2\api_export_files\javacard\framework\javacard\framework.exp
    parsing U:\_Tools\java\43019-560\Annex_B_Export_Files\sim\toolkit\javacard\toolkit.exp
    converting com.gieseckedevrient.jctt.smsTest.StringConsts
    writing D:\save\smsTest\com\gieseckedevrient\jctt\smsTest\javacard\smsTest.exp
    writing D:\save\smsTest\com\gieseckedevrient\jctt\smsTest\javacard\smsTest.jca
    Verifier Error: Exception handlers not sorted in ascending order by the offset of the handler
    Verification failed

    Hello again,
    it seams this error only occurs when using javac from JDK 1.5/1.6 (1.4 not tested).
    When I us jdk1.3.1_11 to compile the java sources this error never occurs during conversion !

Maybe you are looking for

  • Update for the iPod touch 4th gen

    Hi, I have a iPod touch 4th generation running iOS 4.1 (Yes, really old.) And i've never updated an apple device and I need some help about it. I did backup the iPod but when I go to update it, it gives me a warning saying "Some purchased files on he

  • Can I upgrade my Macbook Pro to 16GB RAM

    I am a Graphic Designer and use some very heavy bound software for rendering and running multiple memory munching applications everyday. Lately my macbook pro has been increadibly slow. I have seen allot video on youtube of people upgrading their ram

  • How to display records of int. table in list tree?

    friends,    i want to display a list tree using fm RS_TREE_CONSTRUCT and RS_LIST_DISPLAY. this is the data that i have to display Matnr      doc no.        Stock qty.     Age 1     45601236           100          55 1     45601237           10       

  • Macbook not recognising receiver

    Hi folks, I'm using a MiniDisplay to HDMI cable, to try to connect my MBP to my Denon Home Theatre Receiver. I'm connecting the cable to the Thunderbolt connection on the MBP, and Blu-ray input on the HT receiver. The Mac is not recognising the recei

  • Auto Run ignores URL parameters and uses Defaults on first run

    We have BI Publisher 11g standalone (not OBIEE). We have a suite of BI Publisher reports, all set up on data sets with default parameters. All reports have Auto Run enabled and caching disabled. The reports are run from a Flex UI application using a