math
/* * Name: Hemant Mahato * Class: ADV DATA STRUCTURS,ALGORTHMS I/ CSCI 308/ 21S CSCI308-WHA/ SPRING 2021 * Date: 03/17/2021 */ import java.util.*; public class BubbleSortJava { //Function to print an array static void printArray(int arr[], int size) { int i; for(i = 0; i < size; i++) { System.out.print(arr[i] + " "); } System.out.println(); } //driver program public static void main(String args[]) { Scanner sc = new Scanner(System.in); //declare integer array int arr[] = new int[100]; int n = 0; int num; System.out.println("-->Please enter positive number and press -1 to end list value."); //continue runs and taking number from the console. while(true) { String s = sc.next(); try { //checks if usesr entered integer or not num = Integer.parseInt(s); //if user entered positive integer then store that number to arr if (num != -1) { arr[n] = num; n++; } //if user entered -1 then break the loop else { break; } } //if user enterd other than integer then print the exception catch (NumberFormatException ex) { System.out.println("Please enter positve number or -1"); } } //int arr[] = { 64, 34, 25, 12, 22, 11, 90}; //int n = arr.length; System.out.println("The given array : "); printArray(arr, n); //call bubble sort method to sort the array. bubbleSort(arr, n); System.out.println("Sorted array: "); //call printArray method to print the array. printArray(arr, n); } static void bubbleSort(int arr[], int n) { // An optimized version of bubble Sort int i, j, temp; boolean swapped; for( i = 0; i < n - 1; i++) { swapped = false; for( j = 0; j < n - i - 1; j++) { if(arr[j] > arr[j + 1]) { temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; swapped = true; } } //If no two elements were swapped by inner loop, then break if(swapped == false) break; } } }