Java基礎總結 - 數組排序之插入排序
這篇文章只是把大學記的筆記整理到博客,方便自己查看,不保證權威性(•̀ᴗ•́)و ̑̑
import java.util.Arrays;
/**
* 直接插入排序
* 概念是,假設將數字插入一個有序數列,當array[0]一個數字默認有順序,然後把array[1]比較然後插入,
* 再把array[2]插入array[0]、array[1]有序數列,插入一個數字之前數組默認就是有序了。
*
* @author CL-computer
*
*/
public class InsertSort {
public static void main(String[] args) {
int[] nums = {1,5,7,1,6,9,8,5};
InsertSortMetohd(nums);
System.out.println(Arrays.toString(nums));
}
public static void InsertSortMetohd(int[] nums) {
for(int i = 0;i<nums.length;i++){
for(int j=i;j>0;j--){
if(nums[j-1]>nums[j]){
int temp = 0;
temp = nums[j];
nums[j] = nums[j-1];
nums[j-1] = temp;
}else{
break;
}
}
}
}
}
/**
* 希爾排序:
* 是一種壓縮增量的排序算法
* 這個增量現在大多數選擇 數組長度的一半,但是這不是最好的。
*
* 第一次使用數組長度一半進行跳躍的比較排序,
* 第二次使用數組長度一半的一半,直到gap等於1時數組就有序了
*
* 時間複雜度: n1.3 n n2
* 空間複雜度: 1
*
* @author CL-computer
*
*/
public class ShellSort {
public static void main(String[] args) {
int[] nums = {1,5,7,1,6,9,8,5};
ShellSortMetohd(nums);
System.out.println(Arrays.toString(nums));
}
public static void ShellSortMetohd(int[] nums) {
for(int gap = nums.length/2;gap>0;gap/=2){
for(int i =0;i<nums.length;i++){
for(int j=i+gap;j<nums.length;j+=gap){
if(nums[j]<nums[j-gap]){
int temp = 0;
temp = nums[j];
nums[j] = nums[j-gap];
nums[j-gap] = temp;
}
}
}
}
}
}