Insertion Sort Algorithm-插入排序算法

Insertion Sort is a simple sorting algorithm that works the way

we sort playing cards in our hands.We sort the first two cards and then

place the third card in the appropriate position within the first two,

and then the fourth is positioned within the first three,and so until

the whole hand is sorted.


During an iteration,an element of the list is inserted into the sorted

portion of the array to its left.So,basically,for each iteration,we

have an array of sorted elements to the left,and an array of other

elements still to be sorted to the right.  


for example :

 the array is [4,1,5,2]

step1:[1,4,5,2],start with second element 1 and position it in the

 "array" of the first two the left sorted array is [1,4]

  step2:[1,4,5,2] the next element is 5,insert it properly two the left

  array,then the left sorted array is [1,4,5]

  step3: [1,2,4,5]the next element is 2,insert it properly two the left array  


public void sortElement(int[] elements) {
    int length = elements.length;

    for(int i=0;i<length;i++){
          for(int j=i;j>0;j--){
              }else {



private void swap(int[] elements, int j, int i) {
    int temp=elements[j];

  • 最新评论
  • 总共0条评论
  • Powered by bjyblog modified by Adam © 2014-2023 版权所有 ICP证:鲁ICP备15039297号
  • 联系邮箱