Selection Sort
Given an array of integers, sort the elements in the array in ascending order. The selection sort algorithm should be used to solve this problem.
Examples
- {1} is sorted to {1}
- {1, 2, 3} is sorted to {1, 2, 3}
- {3, 2, 1} is sorted to {1, 2, 3}
- {4, 2, -3, 6, 1} is sorted to {-3, 1, 2, 4, 6}
Corner Cases
- What if the given array is null? In this case, we do not need to do anything.
- What if the given array is of length zero? In this case, we do not need to do anything.
1 public class SelectionSort { 2 3 public int SelectionSort(int[] array){ 4 if (array == null || array.length = 0){ 5 return array; 6 } 7 int index = i; 8 for ( i = 0; i <= array.length; i++){ 9 for (j = i + 1, j <= array.length; j++) { 10 if (array[j] < array[index]) { 11 index = j; 12 } 13 int tem = array[index]; 14 array[index] = array[j]; 15 array[j] = tem; 16 } 17 }return array; 18 19 } 20 }