插入排序算法中未排序的数字
Unsorted didgit in Insertion Sort Algorithm
// this describes the insertion sort algorithm
public class InsertionSort {
public static void main(String[] args) {
//array of unsorted integers
int [] array = { 10, 4, 1, 11, 5, 3, 8, 2, 0, 9};
int n = array.length;
for ( int j = 1; j<n; j++) {
//assign a value to the second element in the array
int key = array[j];
//assign a value to the 1st element in the list
int i = j-1;
//loop executes as long as i>0 and that the element befor the key is greater than the key itself
while( i>0 && array[i]>key) {
//move the bigger element 1 block forward
array[i+1] = array[i];
// keep moving until the element is in the right position
i =i-1;
}
array[i+1] = key;//assign the key to the appropritae location
}
for (int i=0; i<n; i++)
System.out.print(array[i] + " ");
System.out.println();
}
}
这是输出,如您所见,除 10 之外的所有内容都已排序,这在数组中仍然不合适
10 0 1 2 3 4 5 8 9 11
这行有问题:
while( i>0 && array[i]>key) {
第一次迭代,j 等于 1,因此 i 等于 0。您的循环不会 运行,因为 0 不 大于 比零。但是应该是运行,所以条件需要改成"greater than or equals zero":
while( i>=0 && array[i]>key) {
这将解决您的问题。
// this describes the insertion sort algorithm
public class InsertionSort {
public static void main(String[] args) {
//array of unsorted integers
int [] array = { 10, 4, 1, 11, 5, 3, 8, 2, 0, 9};
int n = array.length;
for ( int j = 1; j<n; j++) {
//assign a value to the second element in the array
int key = array[j];
//assign a value to the 1st element in the list
int i = j-1;
//loop executes as long as i>0 and that the element befor the key is greater than the key itself
while( i>0 && array[i]>key) {
//move the bigger element 1 block forward
array[i+1] = array[i];
// keep moving until the element is in the right position
i =i-1;
}
array[i+1] = key;//assign the key to the appropritae location
}
for (int i=0; i<n; i++)
System.out.print(array[i] + " ");
System.out.println();
}
}
这是输出,如您所见,除 10 之外的所有内容都已排序,这在数组中仍然不合适
10 0 1 2 3 4 5 8 9 11
这行有问题:
while( i>0 && array[i]>key) {
第一次迭代,j 等于 1,因此 i 等于 0。您的循环不会 运行,因为 0 不 大于 比零。但是应该是运行,所以条件需要改成"greater than or equals zero":
while( i>=0 && array[i]>key) {
这将解决您的问题。