From b939a3f915cf4fdf2f34e0150f6dc54328bce5e5 Mon Sep 17 00:00:00 2001 From: Achint Srivastava <32853258+achint769muj@users.noreply.github.com> Date: Wed, 5 Dec 2018 04:58:38 +0530 Subject: [PATCH] Added the code for Selection Sort in Java Language (#23465) * Added the code for Selection Sort in Java Language * fix: code block formatting --- .../selection-sort/index.md | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/guide/english/algorithms/sorting-algorithms/selection-sort/index.md b/guide/english/algorithms/sorting-algorithms/selection-sort/index.md index be23b4c273..e08e8bafd1 100644 --- a/guide/english/algorithms/sorting-algorithms/selection-sort/index.md +++ b/guide/english/algorithms/sorting-algorithms/selection-sort/index.md @@ -76,6 +76,30 @@ def seletion_sort(arr): min_i = j arr[i], arr[min_i] = arr[min_i], arr[i] ``` +### Implementation in Java +```java +public void selectionsort(int array[]) +{ + int n = array.length; //method to find length of array + for (int i = 0; i < n-1; i++) + { + int index = i; + int min = array[i]; // taking the min element as ith element of array + for (int j = i+1; j < n; j++) + { + if (array[j] < array[index]) + { + index = j; + min = array[j]; + } + } + int t = array[index]; //Interchange the places of the elements + array[index] = array[i]; + array[i] = t; + } +} +``` + ### Implementation in MATLAB ```MATLAB