简体   繁体   中英

Sorting an array in ascending order in java

I'm trying to solve a java question, where I have to sort the numbers in ascending orders. My code works, until I put a negative in integer in it.

import java.util.Scanner;
import java.util.Arrays;
public class Main {
    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        int input = sc.nextInt();

        int[] numbers = new int[input];

        for (int i = 0; i < numbers.length; i++) {
            int a = sc.nextInt();
            numbers[a] += a;
        }
        for (int i = 1; i < numbers.length; i++) {
                System.out.println(i + " " + numbers[i] / i);
        }
    }
}

I want to set the amount of numbers in the line 9 as input, but I face errors when I enter bigger values or negative integers. Any helps plz?

This is basically what I need to sort out:

input:

5
-3
100
-1
-2
-1

output:

-3 1
-2 1
-1 2
100 1

Arrays.sort() is a built-in function to help you sort the array

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);

    int input = sc.nextInt();
    int[] numbers = new int[input];

    for (int i=0; i <numbers.length; i++) {
        int a = sc.nextInt();
        numbers[i] = a;
    }
    sc.close();

    Arrays.sort(numbers);

    int temp=numbers[0];
    int count=1;
    for(int i=1; i<numbers.length; i++){
        if(numbers[i]==temp){
            count++;
        }else{
            System.out.println(temp + " " + count);
            count=1;
            temp=numbers[i];
        }
    }
    System.out.println(temp + " " + count);
}

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