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

网友投稿 212 2023-08-01


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

/**

* 选择排序的思想:

* 每次循环前,数组左边都vAgWK是部分有序的序列,

* 然后选择右边待排元素,将其值保存下来

* 依次和左边已经排好的元素比较

* 如果小于左边的元素,就将左边的元素右移一位

* 直到和最左边的比较完成,或者待排元素不比左边元素小

*/

package al;

public class InsertionSort {

public sthttp://atic 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++) {

Shttp://ystem.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

int j = i; // current position

key = array[j];

// compare current element

while(j > 0 && arhttp://ray[j-1] > key) {

array[j] = array[j-1]; //shift it

j--;

}

array[j] = key;

}

}

}

int j = i; // current position

key = array[j];

// compare current element

while(j > 0 && arhttp://ray[j-1] > key) {

array[j] = array[j-1]; //shift it

j--;

}

array[j] = key;

}

}

}


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:Java数据结构及算法实例:快速计算二进制数中1的个数(Fast Bit Counting)
下一篇:Java数据结构及算法实例:汉诺塔问题 Hanoi
相关文章

 发表评论

暂时没有评论,来抢沙发吧~