Select the principle of sorting:
Iterate through all the elements, get the smallest element, and swap the smallest element with the first element on the left, and iterate through all the elements in the first position, getting the smallest element and swapping it with the second element on the left. When a second traversal is performed, the smallest element is swapped with the second element on the left, so that the ordered element is then iterated through.
Basic basic steps of demo implementation:
1. Prepare the array
2. Write common array operation methods
3, write the method of selecting sorting
4. Test selection sequencing
Specific references are as follows:
Package com.zcp.ch03;
/**
- @author Administrator
-
Implementation of bubble sort
*/
public class Selectarray {
Array
Private long[] arr = null;
The size of valid data in an array
private int elems;
Public Selectarray () {
arr = new LONG[50];
}
public Selectarray (int length) {
arr = new Long[length];
}
/**
- Operations for inserting data
- @param value
*/
public void Insert (Long value) {
Arr[elems] = value;
elems++;
}
/**
}
/***
- Delete Data operation, Delete succeeded return true, delete failed return false
-
@param value
*/
Public Boolean Delete (Long value) {
int key = find (value);
if (key = =-1) {
System.out.println ("Failed to delete data, no data found to delete");
return false;
}
for (int i = key; I < Elems; i++) {
Arr[i] = arr[i+1];
}
elems--;
return true;
}
/***
- @param oldValue
- @param newvalue
- @return If the modification returns true successfully, the modification fails to return false
*/
public boolean changevalue (Long Oldvalue,long newvalue) {
int key = find (OldValue);
if (key = =-1) {
SYSTEM.OUT.PRINTLN ("The data that needs to be modified does not exist, the modification fails");
return false;
}
Arr[key] = newvalue;
return true;
}
/**
- The method is mainly to realize the choice of sorting
- The specific implementation is described as follows:
- The min in the method represents the smallest element
- The smallest element is placed at the far left of the array after a single traversal, and then the selection is sorted by looping
-
*/
public void Selectsort () {
int min = 0;
Long tmp = 0;
for (int i = 0; i < elems-1; i++) {
for (int j = i; j < elems; j++) { if(arr[min] > arr[j]){ min = j; }}tmp = arr[i];arr[i] = arr[min];arr[min] = tmp;
}
}
/**
- The method is mainly an array of variables and displays
*/
public void DisPlay () {
for (int i = 0; i < Elems; i++) {
System.out.print (arr[i]+ "");
}
System.out.println ();
}
}
The test code is as follows:
Package com.zcp.ch03;
public class Testselectmain {
public static void main(String[] args) { SelectArray bubbleArray = new SelectArray(); bubbleArray.insert(10); bubbleArray.insert(50); bubbleArray.insert(80); bubbleArray.insert(2); bubbleArray.insert(2); bubbleArray.disPlay(); bubbleArray.selectSort();; System.out.println("选择排序后的数据如下:"); bubbleArray.disPlay();}
}
Java Common Data Algorithm _ Select Sort