Created
September 11, 2016 11:16
-
-
Save nichtemna/84947d4f1fa3d7d490840c2a7a8a4746 to your computer and use it in GitHub Desktop.
Selection sort
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package search_sort; | |
import java.util.Scanner; | |
/** | |
* | |
Selection sort O(n2): | |
Find the minimum by scanning the array | |
Swap it with the first element | |
Increment index and repeat with the remaining part of the array | |
*/ | |
public class SelectionSort { | |
public static void main(String[] args) { | |
Scanner scanner = new Scanner(System.in); | |
int n = scanner.nextInt(); | |
int[] array = new int[n]; | |
for (int i = 0; i < n; i++) { | |
array[i] = scanner.nextInt(); | |
} | |
array = getArraySorted(array); | |
for (int i : array) { | |
System.out.print(i + " "); | |
} | |
} | |
private static int[] getArraySorted(int[] array) { | |
for (int i = 0; i < array.length; i++) { | |
int smallestIndex = findSmallest(array, i); | |
array = swap(array, i, smallestIndex); | |
} | |
return array; | |
} | |
private static int findSmallest(int[] array, int i) { | |
int smallestIndex = i; | |
for (int j = i + 1; j < array.length; j++) { | |
if (array[smallestIndex] > array[j]) { | |
smallestIndex = j; | |
} | |
} | |
return smallestIndex; | |
} | |
private static int[] swap(int[] array, int i, int j) { | |
int temp = array[i]; | |
array[i] = array[j]; | |
array[j] = temp; | |
return array; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment