Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class SelectionSortHomeWork {
- public static void main(String[] args) {
- int[] array = {5, 3, 9, 7, 4, 1};
- selectionSort(array);
- printArray(array);
- }
- static void printArray(int[] arr) {
- for (int i = 0; i < arr.length; i++) {
- System.out.print(arr[i] + " ");
- }
- }
- static void selectionSort(int[] arr) {
- for (int x = 0; x < arr.length/2; x++) {
- int min = arr[x];
- int minIndex = x;
- int max = arr[x];
- int maxIndex = x;
- for( int i = x + 1; i < arr.length-1-x; i++) {
- if(arr[i] < min) {
- min = arr[i];
- minIndex = i;
- }
- if(arr[i] > max) {
- max = arr[i];
- maxIndex = i;
- }
- }
- int temp = arr[x];
- arr[x] = arr[minIndex];
- arr[minIndex] = temp;
- if(minIndex == arr.length-1) {
- minIndex = maxIndex;
- }
- temp = arr[x];
- arr[x] = arr[maxIndex];
- arr[maxIndex] = temp;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement