不使用arrays.sort按升序对随机数组进行排序

时间:2017-04-18 20:40:01

标签: java

我试图在不使用arrays.sort的情况下对随机数组进行排序。我有代码,但它不起作用。不确定错误在哪里。任何形式的帮助表示赞赏。

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;
    }
}

1 个答案:

答案 0 :(得分:1)

你的行

library(shinythemes)
library(shiny)
library(rhandsontable)

ui <- fluidPage(theme = shinytheme("slate"),titlePanel(HTML("<h1> <font face=\"Rockwell Extra Bold\" color=\"#b42000\"><b><b>R/Econ</b></b></font> <font face=\"Lucida Calligraphy\" colsor=\"white\" >Model</font></h1>")),
                sidebarLayout(
                  sidebarPanel( 
                    numericInput("rows", label = h3("Number of Rows"), value = 20),
                    numericInput("cols", label = h3("Number of Columns"), value = 2)
                  ),
                  mainPanel(
                    rHandsontableOutput("tbl")
                  )
                )
)

server <- function(input, output, session) {

  data = reactive({
    if (is.null(input$tbl))  {
        DF <- data.frame(num1 = 1:input$rows, bool = TRUE, nm = LETTERS[1:input$rows],
                        dt = seq(from = Sys.Date(), by = "days", length.out = input$rows),
                        stringsAsFactors = F)

    } else  if(nrow(hot_to_r(input$tbl)) == input$rows) {
        DF <- hot_to_r(input$tbl)
      } else {
        DF <- data.frame(num1 = 1:input$rows, bool = TRUE, nm = LETTERS[1:input$rows],
                dt = seq(from = Sys.Date(), by = "days", length.out = input$rows),
                stringsAsFactors = F)
    }
    DF
  })

  output$tbl <- renderRHandsontable({
if (is.null(input$rows) | is.null(input$cols)) return()
    df = data()
    if (!is.null(df))
      rhandsontable(df, stretchH = "all")
  })

}

shinyApp(ui = ui, server = server)

应该是

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

或者,删除“-1”并保持“&lt;”。否则,您将忽略数组中的最后一个数字。其他一切看起来都不错。