pure-jcore/src/main/java/leetcode/sorting/Answers.java
/*
	 * Selection Sort has almost same logic but different perspective from bubble sort.
	 * Time: O(n^2), Space: O(1).
	 */
Selection Sort has almost same logic but different perspective from bubble sort.
Selection Sort has almost same logic but different perspective from bubble sort .
public static int[] selectionSort(int[] arr) {
		int len = arr.length;
		for (int i=0; i<len; i++) {
			int max = 0;
			for (int j=0; j<(len - i); j++) {
				int a = arr[j];
				int b = arr[max];
				if (a > b) {
					max = j;
				}
			}
			int pos = len - 1 - i;
			if (pos != max) {
				swap(arr, max, pos);
			}
		}
		return arr;
	}
public static int [ ] selectionSort ( int [ ] arr ) { int len = arr . length ; for ( int i = 0 ; i < len ; i ++ ) { int max = 0 ; for ( int j = 0 ; j < ( len - i ) ; j ++ ) { int a = arr [ j ] ; int b = arr [ max ] ; if ( a > b ) { max = j ; } } int pos = len - 1 - i ; if ( pos != max ) { swap ( arr , max , pos ) ; } } return arr ; }
Selection Sort has almost same logic but different perspective from bubble sort.
Selection Sort has almost same logic but different perspective from bubble sort .
// for n times, one correct number at one time // for m times, each time traverse from the 0 to the (length -1 -i). // swap max and the position