From 87167fc6c7f7858cf75c4998b7289278f9d87cb1 Mon Sep 17 00:00:00 2001 From: Vladimir GS Date: Sat, 24 Oct 2020 18:43:26 -0500 Subject: [PATCH] Add descending order for bubblesort As part of CCOSS 2020 contribution I'd like to add sort option --- Java/BubbleSort.java | 97 ++++++++++++++++++++++++++++---------------- 1 file changed, 63 insertions(+), 34 deletions(-) diff --git a/Java/BubbleSort.java b/Java/BubbleSort.java index 9135155..61044ec 100644 --- a/Java/BubbleSort.java +++ b/Java/BubbleSort.java @@ -1,39 +1,68 @@ import java.util.Scanner; -public class BubbleSort { +public class BubbleSort { + + static void bubbleSortAsc(int arr[], int n) { + int tmp; + boolean flag; - public static void main(String args[]) { - Scanner sc = new Scanner(System.in); - System.out.print("Enter the number of elements : "); - int n = sc.nextInt(); - int arr[] = new int[n]; - System.out.println("Enter " + n + " elements :"); - for (int i = 0; i < n; i++) - arr[i] = sc.nextInt(); + for (int i = 0; i < n - 1; i++) { + flag = false; + for (int j = 0; j < n - i - 1; j++) { + if (arr[j] > arr[j + 1]) { + tmp = arr[j]; + arr[j] = arr[j + 1]; + arr[j + 1] = tmp; + flag = true; + } + } + if (!flag) + break; + } + } + + static void bubbleSortDesc(int arr[], int n) { + int tmp; + boolean flag; - bubbleSort(arr); - - System.out.println("\nThe sorted array : ;"); - for (int i = 0; i < n; i++) - System.out.print(arr[i] + " "); - System.out.println(); - } - - static void bubbleSort(int arr[]) { - int len = arr.length, tmp; - boolean flag; - for (int i = 0; i < len; i++) { - flag = false; - for (int j = 0; j < len - i - 1; j++) { - if (arr[j] > arr[j + 1]) { - tmp = arr[j]; - arr[j] = arr[j + 1]; - arr[j + 1] = tmp; - flag = true; - } - } - if (!flag) - break; - } - } + for (int i = 0; i < n - 1; i++) { + flag = false; + for (int j = 0; j < n - i - 1; j++) { + if (arr[j] < arr[j + 1]) { + tmp = arr[j]; + arr[j] = arr[j + 1]; + arr[j + 1] = tmp; + flag = true; + } + } + if (!flag) + break; + } + } + + public static void main(String args[]) { + Scanner sc = new Scanner(System.in); + System.out.print("Indicate the number of elements: "); + int order; + boolean asc; + int n = sc.nextInt(); + int arr[] = new int[n]; + + System.out.println("Type " + n + " numbers: "); + for (int i = 0; i < n; i++) + arr[i] = sc.nextInt(); + + System.out.println("Indicate desired order (0 for Ascending, 1 for Descending):"); + order = sc.nextInt(); + asc = order == 0 ? true : false; + if (asc) + bubbleSortAsc(arr, arr.length); + else + bubbleSortDesc(arr, arr.length); + System.out.println("The sorted array : "); + for (int i = 0; i < n; i++) + System.out.print(arr[i] + " "); + System.out.println(); + sc.close(); + } }