Java array sorting - selection sort

The selection sorting of Java array sorting is to compare the elements with the smallest index with the following elements in turn, and the small elements are placed in the front. After the first comparison, the smallest element will be displayed at the leftmost with the smallest index, and the same can be done later. get a sorted array

Selection sort is also regular:

1 is first compared with the following elements from 0 index,

   The second time is from the 1 index and the following element is compared. . .

2 The last comparison is the index element of length-2 of the array and the index element of array length-1

Also draw a picture to help understand

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Run the code to see the result

public class SelectDemo {
	public static void main(String[] args) {
		int[] arr = new int[] { 2, 34, 56, 43, 45 };

		int[] arr2 = getSelect(arr);
		for (int a : arr2) {
			System.out.print(a + " ");
		}
	}

	public static int[] getSelect(int[] arr2) {
		for (int i = 0; i < arr2.length - 1; i++) {
			int minIndex = i;
			for (int j = i + 1; j < arr2.length; j++) {
				if (arr2[minIndex] > arr2[j]) {
					minIndex = j;
				}
			}
			if (arr2[minIndex] != arr2[i]) {
				int temp = arr2 [minIndex];
				arr2[minIndex] = arr2[i];
				arr2[i] = temp;
			}
		}
		return arr2;

	}

}





Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325641926&siteId=291194637