Answer to Question #286295 in Java | JSP | JSF for Mage

Question #286295

Write a program to store 15 numbers in an array. Then display all negative numbers in ascending order using bubble sorting.


1
Expert's answer
2022-01-11T09:44:42-0500
import java.util.InputMismatchException;
import java.util.Scanner;


public class Main {
    private static void ascendingBubbleSorting(int[] arr) {
        boolean sorted = false;
        int tmp;


        while (!sorted) {
            sorted = true;


            for (int i = 0; i < arr.length - 1; i++) {
                tmp = arr[i];


                if (tmp > arr[i + 1]) {
                    arr[i] = arr[i + 1];
                    arr[i + 1] = tmp;
                    sorted = false;
                }
            }
        }
    }


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


        int arr[] = new int[15];
        int negativeCounter = 0;


        System.out.println("Enter " + arr.length + " numbers:");
        for (int i = 0; i < arr.length; i++) {
            while (true) {
                try {
                    arr[i] = input.nextInt();
                    if (arr[i] < 0) negativeCounter++;
                    break;
                } catch (InputMismatchException e) {
                    System.out.println("The entered number is incorrect, please try again...");
                    input.next();
                }
            }
        }


        if (negativeCounter == 0) {
            System.out.println("Negative numbers not found!");
            return;
        }


        int newArr[] = new int[negativeCounter];
        int i2 = 0;
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] < 0) {
                newArr[i2] = arr[i];
                i2++;
            }
        }


        ascendingBubbleSorting(newArr);


        System.out.println("Negative numbers in ascending order:");
        for (int i = 0; i < newArr.length; i++) {
            System.out.print(newArr[i] + " ");
        }
        System.out.println();
    }
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog