From dbf25ab681c813be8a988b9ffa6109e2f67bdd0d Mon Sep 17 00:00:00 2001 From: praveer7398 <134937008+praveer7398@users.noreply.github.com> Date: Mon, 23 Oct 2023 19:24:30 +0530 Subject: [PATCH] Add files via upload --- Java/sorting techniques/bubble_sort.java | 59 +++++++++++++++++++++ Java/sorting techniques/insertion_sort.java | 41 ++++++++++++++ 2 files changed, 100 insertions(+) create mode 100644 Java/sorting techniques/bubble_sort.java create mode 100644 Java/sorting techniques/insertion_sort.java diff --git a/Java/sorting techniques/bubble_sort.java b/Java/sorting techniques/bubble_sort.java new file mode 100644 index 00000000..bb730418 --- /dev/null +++ b/Java/sorting techniques/bubble_sort.java @@ -0,0 +1,59 @@ + + +import java.util.Scanner; + +class bubble_sort { + + + static void bubbleSort(int arr[], int n) + { + 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 (swapped == false) + break; + } + } + + + static void printArray(int arr[], int size) + { + int i; + for (i = 0; i < size; i++) + System.out.print(arr[i] + " "); + System.out.println(); + } + + + public static void main(String[] args) { + try (Scanner scanner = new Scanner(System.in)) { + int n = scanner.nextInt(); + int[] arr = new int[n]; + + + for (int i = 0; i < n; i++) { + arr[i] = scanner.nextInt(); + } + + bubbleSort(arr, n); + + printArray(arr, n); + } + } +} + +// This code is contributed +// by Nikita Tiwari. diff --git a/Java/sorting techniques/insertion_sort.java b/Java/sorting techniques/insertion_sort.java new file mode 100644 index 00000000..3d479ea0 --- /dev/null +++ b/Java/sorting techniques/insertion_sort.java @@ -0,0 +1,41 @@ +import java.util.Scanner; + +public class insertion_sort { + public static void insertionSort(int n, int[] arr) { + for (int i = 1; i < n; ++i) { + int curr = arr[i]; + int idx = i - 1; + + while (idx >= 0 && arr[idx] > curr) { + arr[idx + 1] = arr[idx]; + --idx; + } + + arr[idx + 1] = curr; + } + } + + public static void main(String[] args) { + Scanner scanner = new Scanner(System.in); + + + int n = scanner.nextInt(); + int[] arr = new int[n]; + + + for (int i = 0; i < n; i++) { + arr[i] = scanner.nextInt(); + } + + + + insertionSort(n, arr); + + + for (int num : arr) { + System.out.print(num + " "); + } + + scanner.close(); + } +}