Java插入排序 Insertion Sort Java数据结构及算法实例:插入排序 Insertion Sort

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Java插入排序 Insertion Sort Java数据结构及算法实例:插入排序 Insertion Sort

  2021-03-21 我要评论
想了解Java数据结构及算法实例:插入排序 Insertion Sort的相关内容吗,在本文为您仔细讲解Java插入排序 Insertion Sort的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:Java,数据结构,算法,插入排序,Insertion,Sort,下面大家一起来学习吧。
/** 
 * 选择排序的思想: 
 * 每次循环前,数组左边都是部分有序的序列, 
 * 然后选择右边待排元素,将其值保存下来 
 * 依次和左边已经排好的元素比较 
 * 如果小于左边的元素,就将左边的元素右移一位 
 * 直到和最左边的比较完成,或者待排元素不比左边元素小 
 */ 
package al; 
public class InsertionSort { 
   
  public static void main(String[] args) { 
     
    InsertionSort insertSort = new InsertionSort(); 
    int[] elements = { 14, 77, 21, 9, 10, 50, 43, 14 }; 
    // sort the array 
    insertSort.sort(elements); 
    // print the sorted array 
    for (int i = 0; i < elements.length; i++) { 
      System.out.print(elements[i]); 
      System.out.print(" "); 
    } 
  } 
   
  /** 
   * @author 
   * @param array 待排数组 
   */ 
  public void sort(int[] array) { 
    // min to save the minimum element for each round 
    int key; // save current element 
    for(int i=0; i<array.length; i++) { 
      int j = i;  // current position 
      key = array[j]; 
      // compare current element 
      while(j > 0 && array[j-1] > key) { 
        array[j] = array[j-1]; //shift it 
        j--;  
      } 
      array[j] = key; 
     
    } 
  } 
} 

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们