Ich habe versucht, diesen Insertion Sort-Pseudocode in Java zu konvertieren, aber bekomme nicht die richtige Ausgabe. Hier ist der Pseudocode
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
Und hier ist mein Java-Code
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);
}
}
Was ausgedruckt wird, ist genau das gleiche Array A. Nicht sortiert oder irgendetwas nur {5,2,4,6,1,3}.
Antworten:
1 für die Antwort № 1public class InsertionSort {
private static long[] arr;
/**
* Run Insertion Sort algorithm
*
* @param array data structure used to run the algorithm
*/
public static void run(long[] array) {
arr = array;
int j;
for (int i = 1; i < arr.length; i++) {
long temp = arr[i];
j = i;
while (j > 0 && temp <= arr[j - 1]) {
arr[j] = arr[j - 1];
j--;
}
arr[j] = temp;
}
}
}
0 für die Antwort № 2
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);
}
}