简体   繁体   中英

Sort random array in ascending order without arrays.sort

I am trying to sort an array of random numbers without using the arrays.sort. I have the code, but it doesn't work. not sure where is the error. Any kind of help is appreciated.

import java.util.*;
public class Sort
{
    public static void main(String args[])
    {
        Scanner in = new Scanner(System.in);
        System.out.print("How many numbers do you want? ");
        int howMany = in.nextInt();
        int [] myArray =  getRandomArray(howMany);

    }

    /* public static int bsearch(int[] arr, int key)
    {

    }*/

    public static int[] getRandomArray(int howMany) {
        int[] returnMe = new int[howMany]; // Assume size >= 0
        Random rand = new Random();
        for (int i = 0; i < howMany ; i++) 
        returnMe[i] = rand.nextInt(Integer.MAX_VALUE) + 1;
        //System.out.print(returnMe[i] + " ");
        for (int i = 1; i <= (howMany - 1); i++)
        {
            for (int j = 0; j < howMany - i -1; j++) 
            {
                int tmp = 0;
                if (returnMe[j] > returnMe[j+1])
                {
                    tmp = returnMe[j];
                    returnMe[j] = returnMe[j + 1];
                    returnMe[j + 1] = tmp; 
                }   
            }  
        }
        for ( int i = 0; i < howMany; i++)
            System.out.println(returnMe[i] + " "); 
        return returnMe;
    }
}

Your line

        for (int j = 0; j < howMany - i -1; j++) 

should be

        for (int j = 0; j <= howMany - i -1; j++) 

or alternatively, remove the "-1" and keep "<". Otherwise, you will ignore the last number in the array. Everything else looks fine to me.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM