Select a Sort concept
Selection sorting is also an exchange sorting algorithm, and bubble sort has a certain degree of similarity, so the individual thinks that the choice of ordering can be considered as a bubble sort of an improved algorithm. The idea is this:
Set now to sort the array arr[], it has n elements.
1 Compare the first element (Java, subscript 0) with the second element, if the former is greater than the latter, then it must not be minimal, but we are not as eager to swap as the bubble sort. We can set a temporary variable A to store the subscript for the currently smallest element. And then we'll continue to compare the smallest element to the third, and if it's not the smallest, then we'll modify the value of a. So until you're finished with the last element, you can be sure that a store must be the subscript for the smallest element.
2. If the value of A is not 0 (the initial value, that is, the subscript of the first element), swap the two elements labeled A and 0.
3. Repeat the above process, this time from the subscript 1 elements start to compare, because the subscript 0 position has been put the smallest element.
4. So until only the last element is left, it is certain that the element is the largest.
5. Sorting completed.
Obviously, this algorithm also needs to n-1 the wheel sort.
It should be noted that the above is only the way to find the minimum value each time. You can actually find the maximum value each time, but you need to put it on the array's tail every time.
Java implementation code:
Selectarray.java
Package ch02;
public class Selectarray {
//array
private long[] arr;
The size of the valid data in the array
private int elems;
Default constructor public
Selectarray () {
arr = new long[50];
}
Public Selectarray (int max) {
arr = new Long[max];
}
Insert data public
void Insert (Long value) {
Arr[elems] = value;
elems++;
}
Display data public
void display () {for
(int i = 0; i < Elems; i++) {
System.out.print (Arr[i] + "");
}
System.out.println ();
}
Select sort public
void Selectsort () {
int min = 0;
Long tmp = 0L;
for (int i = 0; i < elems-1 i++) {
min = i;
for (int j = i + 1; j < Elems; J + +) {
if (Arr[j] < arr[min]) {
min = j;
}
}
TMP = Arr[i];
Arr[i] = arr[min];
Arr[min] = tmp;}}}
Test code:
Package ch02;
public class Testselectarray {public
static void Main (string[] args) {
Selectarray sArr = new Selectarray ();
Sarr.insert (MR);
Sarr.insert (WU);
Sarr.insert (667);
Sarr.insert (7);
Sarr.insert (a);
Sarr.insert (a);
Sarr.insert (a);
Sarr.display ();
Sarr.selectsort ();
Sarr.display ();
}
Results: