"options": {
"legend": {
"display": true
},
"scales": {
"xAxes": [{
"display": true
}
],
"yAxes": [{
"display": true,
"ticks": {
"min": 0,
"max": 40
}
}
]
},
"tooltips": {
"enabled": true,
"backgroundColor": "#eee",
"titleFontColor": "#000"
},
"annotation": {
"annotations": [{
"type": "box",
"xScaleID": "x-axis-0",
"yScaleID": "y-axis-0",
"yMin": 0,
"yMax": 15,
"xMin": 864,
"xMax": 1285,
"borderWidth": 1,
"backgroundColor": "rgba(200,60,60,0.25)",
"borderColor": "rgba(200,60,60,0.25)"
}, {
"type": "box",
"xScaleID": "x-axis-0",
"yScaleID": "y-axis-0",
"yMin": 30,
"yMax": 40,
"xMin": 864,
"xMax": 1285,
"borderWidth": 1,
"backgroundColor": "rgba(60,60,200,0.25)",
"borderColor": "rgba(60,60,200,0.25)"
}
]
}
}
这是输出,正如您所看到的,除了10之外,所有内容都进行了排序,而10在数组中仍然不合适
// 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();
}
}
答案 0 :(得分:0)
此行有问题:
while( i>0 && array[i]>key) {
第一次迭代,j等于1,所以i等于0。并且您的循环无法运行,因为0 更大不为零。但是它应该运行,因此条件需要更改为“大于或等于零”:
while( i>=0 && array[i]>key) {
这将解决您的问题。