2025-01-16 插入排序
This commit is contained in:
parent
d275f990ac
commit
b1758784c7
106
src/dataANDcalc/java/SortAlgori/InsertSort.java
Normal file
106
src/dataANDcalc/java/SortAlgori/InsertSort.java
Normal file
@ -0,0 +1,106 @@
|
||||
package SortAlgori;
|
||||
|
||||
public class InsertSort {
|
||||
|
||||
private int[] arr;
|
||||
|
||||
private int[] sort;
|
||||
|
||||
private SortNode head = new SortNode();
|
||||
|
||||
public InsertSort(int[] arr){
|
||||
this.arr = arr;
|
||||
this.sort = new int[arr.length];
|
||||
this.sort[0] = arr[0];
|
||||
|
||||
head.next = new SortNode(arr[0]);
|
||||
}
|
||||
|
||||
private void sort(){
|
||||
for (int i = 1; i <arr.length; i++){
|
||||
// 获取本轮需要插入的数,并初始化一个下标为排序数组的最后一个下标
|
||||
int temp = arr[i];
|
||||
int index = i-1;
|
||||
// 当下标小于0就意味着已经完成本轮找位置的过程
|
||||
// 如果当前插入的数小于下标指向的数,需要将当前下标数往后移动移位,并且下标要继续往前移动
|
||||
// 直到下标小于0或者当前插入数大于下标位置的数
|
||||
while (index >=0 && temp < sort[index]){
|
||||
sort[index+1] = sort[index];
|
||||
index --;
|
||||
}
|
||||
//将当前数插入到下标+1的位置
|
||||
sort[index+1] = temp;
|
||||
}
|
||||
}
|
||||
|
||||
private void sortByLinkedList(){
|
||||
for(int i=1; i<arr.length; i++){
|
||||
SortNode node = new SortNode(arr[i]);
|
||||
SortNode temp = head;
|
||||
if(head.next == null){
|
||||
System.out.println("没有设置初始化元素,请检查待排序数组是否为空");
|
||||
return;
|
||||
}
|
||||
while(true){
|
||||
if (temp.next == null){
|
||||
temp.next = node;
|
||||
break;
|
||||
}
|
||||
if(arr[i]<temp.next.node){
|
||||
node.next = temp.next;
|
||||
temp.next = node;
|
||||
break;
|
||||
}
|
||||
temp = temp.next;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public void show(){
|
||||
for (int i = 0; i < sort.length; i++) {
|
||||
System.out.print(sort[i] + " ");
|
||||
}
|
||||
System.out.println();
|
||||
}
|
||||
|
||||
public void showByLinkedList(){
|
||||
SortNode temp = head.next;
|
||||
while(true){
|
||||
if(temp == null){
|
||||
break;
|
||||
}
|
||||
System.out.print(temp.node + " ");
|
||||
temp = temp.next;
|
||||
}
|
||||
}
|
||||
|
||||
public static class SortNode{
|
||||
private int node;
|
||||
|
||||
private SortNode next;
|
||||
|
||||
public SortNode() {
|
||||
}
|
||||
public SortNode(int node) {
|
||||
this.node = node;
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
int[] arr = new int[50000];
|
||||
System.out.println("排序前的序列:");
|
||||
for(int i=0; i<50000; i++){
|
||||
arr[i] = (int)(Math.random()*100000);
|
||||
System.out.print(arr[i] + " ");
|
||||
}
|
||||
System.out.println();
|
||||
InsertSort insertSort = new InsertSort(arr);
|
||||
long startTime = System.currentTimeMillis();
|
||||
insertSort.sort();
|
||||
long endTime = System.currentTimeMillis();
|
||||
System.out.println("排序后的序列:");
|
||||
insertSort.show();
|
||||
System.out.println("排序所花费的时间:" + (endTime - startTime) + "ms");
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user