diff --git a/Sort/Java/SelectionSort.java b/Sort/Java/SelectionSort.java new file mode 100644 index 0000000..106e1bc --- /dev/null +++ b/Sort/Java/SelectionSort.java @@ -0,0 +1,42 @@ +public class SelectionSort { + + public static void main(String a[]) { + int[] arr1 = { 9, 14, 3, 2, 43, 11, 58, 22 }; + System.out.println("Before Sort"); + for (int i : arr1) { + System.out.print(i + " "); + } + System.out.println(); + + sort(arr1, 0, arr1.length-1);// sorting array using insertion sort + + System.out.println("After Sort"); + for (int i : arr1) { + System.out.print(i + " "); + } + } + + public static void sort(int[] array, int leftIndex, int rightIndex) { + if (array != null && leftIndex < rightIndex && leftIndex >= 0 && rightIndex >= 0 && array.length > 0 + && array.length >= rightIndex) { + + for (int i = leftIndex; i < rightIndex; i++) { + int indiceDoMenor = i; + for (int j = i + 1; j <= rightIndex; j++) { + if (array[j] < (array[indiceDoMenor])) + indiceDoMenor = j; + } + swap(array, indiceDoMenor, i); + } + } + } + + public static void swap(int[] array, int i, int j) { + if (array == null) + throw new IllegalArgumentException(); + + int temp = array[i]; + array[i] = array[j]; + array[j] = temp; + } +}