From f72dc5d3bfb155a9363ef805a9116d9899fbeb6d Mon Sep 17 00:00:00 2001 From: Hardik510 <71917334+Hardik510@users.noreply.github.com> Date: Thu, 29 Sep 2022 18:30:30 +0530 Subject: [PATCH] Create bubbleSort.java bubble sort in java --- 1_Arrays/bubbleSort.java | 49 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 1_Arrays/bubbleSort.java diff --git a/1_Arrays/bubbleSort.java b/1_Arrays/bubbleSort.java new file mode 100644 index 0000000..3cd5a3d --- /dev/null +++ b/1_Arrays/bubbleSort.java @@ -0,0 +1,49 @@ +import java.util.*; +public class bubbleSort { + + public static void bubble_sort(int arr[], int n){ + for(int turn = 0; turn < n-1; turn++){ + for(int j = 0; j < n-turn-1; j++){ + if(arr[j] > arr[j+1]){ + // swap + int temp = arr[j]; + arr[j] = arr[j+1]; + arr[j+1] = temp; + } + } + } + } + + public static void bubble_sort_optimized(int arr[], int n){ + for(int turn = 0; turn < n-1; turn++){ + int swaps = 0; + for(int j = 0; j < n-turn-1; j++){ + if(arr[j] > arr[j+1]){ + // swap + int temp = arr[j]; + arr[j] = arr[j+1]; + arr[j+1] = temp; + swaps++; + } + } + if(swaps == 0){ + break; + } // this will break the loop if remaining array or full array is already sorted and will not run test cases for each iteraltion and each element. + } + } + public static void main(String[] args) { + Scanner sc = new Scanner(System.in); + int n = sc.nextInt(); + int arr[] = new int[n]; + for(int i = 0; i < n; i++){ + arr[i] = sc.nextInt(); + } + + bubble_sort_optimized(arr, n); + + for(int i = 0; i < n; i++){ + System.out.print(arr[i] + " "); + } + sc.close(); + } +}