The core idea of inserting sort:
Extract an element and find the appropriate position in the element in front of it to insert.
The reference implementation is as follows:
Package com.zcp.ch04;
/**
- @author Administrator
-
Implementation of bubble sort
*/
public class Insertarray {
Array
Private long[] arr = null;
The size of valid data in an array
private int elems;
Public Insertarray () {
arr = new LONG[50];
}
public Insertarray (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;
}
/**
- Algorithm for inserting sorting
- Inserts an element, finds the appropriate position in the element in front of it, and inserts it
- Analysis: From the definition of insert sort, it can be seen that inserting an element in the element in front of it finds the appropriate position to insert
-
So: When we look for this element we need to start with the second element (the array's subscript is 1), then look for the following element
*/
public void Insertsort () {
Long keyValue = 0;
The purpose of defining I here is the coordinates of the elements we need to find.
for (int i = 1; i < Elems; i++) {
Get to an element we're looking for
KeyValue = Arr[i];
int j = 0;
for (j = i; ((J > 0) && (arr[j-1] > KeyValue)); j--) {
By judging the value of the arr[j-1]>keyvalue inside, move the whole right and leave the leftmost position.
ARR[J] = arr[j-1];
}
Inserts the selected data to the leftmost
ARR[J] = KeyValue;
}
}
/**
- 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 demo is as follows:
Package com.zcp.ch04;
public class Testinsertmain {
public static void main(String[] args) { InsertArray bubbleArray = new InsertArray(); bubbleArray.insert(10); bubbleArray.insert(500); bubbleArray.insert(80); bubbleArray.insert(2); bubbleArray.insert(23); bubbleArray.disPlay(); bubbleArray.insertSort();;; System.out.println("选择排序后的数据如下:"); bubbleArray.disPlay();}
}
Java Common Data Algorithm _ insert Sort