From d159ca5e88960dac8137a8a99ba670ca42d622eb Mon Sep 17 00:00:00 2001 From: kasch309 Date: Mon, 26 Oct 2020 11:40:46 +0100 Subject: [PATCH] Add bubblesort and selectionsort for java --- java/BubbleSort.java | 17 +++++++++++++++++ java/SelectionSort.java | 19 +++++++++++++++++++ 2 files changed, 36 insertions(+) create mode 100644 java/BubbleSort.java create mode 100644 java/SelectionSort.java diff --git a/java/BubbleSort.java b/java/BubbleSort.java new file mode 100644 index 0000000..f21f841 --- /dev/null +++ b/java/BubbleSort.java @@ -0,0 +1,17 @@ +public class BubbleSort{ + + public static void swap (int [] arr, int i, int j){ + int temp = arr[i]; + arr[i] = arr[j]; + arr[j] = temp; + } + + public static void bubbleSort(int[] arr){ + for (int i = 0; i < arr.length; i++){ + if (arr[i] > arr[i+1]){ + swap(arr, i, i+1); + i = 0; + } + } + } +} \ No newline at end of file diff --git a/java/SelectionSort.java b/java/SelectionSort.java new file mode 100644 index 0000000..9082e37 --- /dev/null +++ b/java/SelectionSort.java @@ -0,0 +1,19 @@ +public class SelectionSort{ + + public static void swap (int [] arr, int i, int j){ + int temp = arr[i]; + arr[i] = arr[j]; + arr[j] = temp; + } + + public static void selectionSort(int [] arr){ + int lowestPos = 0; + for (int i = 0; i < arr.length; i++){ + for (int j = i; j < arr.length; j++){ + if (arr[lowestPos] > arr[j]) lowestPos = j; + swap (arr, lowestPos, i); + lowestPos = i+1; + } + } + } +} \ No newline at end of file