我试图将此插入排序伪代码转换为 java,但没有得到正确的输出。这是伪代码
INSERTION-SORT(A)
1 for j ← 2 to length[A]
2 do key ← A[j]
3 ▹ Insert A[j] into the sorted sequence A[1 j - 1].
4 i ← j - 1
5 while i > 0 and A[i] > key
6 do A[i + 1] ← A[i]
7 i ← i - 1
8 A[i + 1] ← key
这是我的Java代码
public class Insertion {
public static void print(int[] A){
for(int i = 0; i > A.length; i++){
System.out.print(A[i] + " ");
}
System.out.println();
}
public static void insertionSort(int[] A){
for(int j = 1; j < A.length; j++){
int key = A[j];
int i = j - 1;
while(i >= 0 && A[i] > key){
A[i + 1] = A[i];
i = i - 1;
}
key = A[i + 1];
}
print(A);
}
public static void main(String[] args){
int[] x = {5,2,4,6,1,3};
insertionSort(x);
}
}
打印出来的只是同一个数组 A。未排序或只是 {5,2,4,6,1,3}。