0% found this document useful (0 votes)
2 views7 pages

Bubble Sort with User Input in Java

THIS MOR E IMPORTANT To learners

Uploaded by

prove143d
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views7 pages

Bubble Sort with User Input in Java

THIS MOR E IMPORTANT To learners

Uploaded by

prove143d
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

import [Link].

Scanner;

public class BubbleSortUserInput


{

public static void main(String[]


args) {
//create Scanner object
Scanner BubbleSort = new
Scanner([Link]);
int[] numbers = new int[10];
// print 10 random input integers
[Link]("Enter 10
Random numbers:");

// Arrays to execute the


input conditions
for (int i = 0; i < 10; i++) {
[Link]("Enter
number " + (i + 1) + ": ");
numbers[i] =
[Link]();//close the
scanner
}

//print Unsorted array


[Link]("Unsorted
array:");
printArray(numbers);

bubbleSort(numbers);//calls
for bubbleSort() method

[Link]("Sorted
array:");
printArray(numbers);

[Link](); // Close
the scanner to prevent resource
leaks
}
// sort arrays using
bubbleSort(arr)
public static void
bubbleSort(int[] arr) {
//get the length of array
int n = [Link];
boolean swapped;//Checkd
tru or false statement
//for loops for false condition
for (int i = 0; i < n - 1; i++) {
swapped = false;
//Introducing "j' to navigate the
array during the bubbleSort,
allowing codes to compare and
swap adjacent elements
for (int j = 0; j < n - i - 1; j+
+) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
swapped = true;
}
}
//stop when the statement
becomes false,can also be
written as(!swapped) or(!
(swapped==true))
if(swapped==false){
break;
}
}
}
//call the printArray() method

public static void


printArray(int[] arr) {
//4 loops condition for input
array value
for (int value : arr) {
[Link](value + "
");
}
[Link]();
}
}
//thanks by
Amicablejames@[Link]

You might also like