下面是主要方法調用了插入不同大小的多個數組的insertSort方法。在這個例子中我只有一個數組,但是有多個數組將會被運行。我無法弄清楚如何讓arr2像插入排序那樣排序。從arr2的末端開始向上推,直到它到達arr2中的正確點,然後再次查看未排序的數組,然後將下一個數字放在arr2的末尾,然後重複排序,直到出現排序如果你能幫助我,這將是很好的。是的,我查看了其他代碼,但沒有人幫助我解決問題,我花了一個星期的時間來解決這個問題。Java插入排序
static void insertionSort(int[] arr) {
final long startTime = System.nanoTime(); // starts timer
System.out.println("Insertion Sort");
//************** Code For Sorting *****************//
int[] sorted = Arrays.copyOf(arr, arr.length); // Copies unsorted array to new array
Arrays.sort(sorted); // sorts unsorted array for compairison later on
int[] arr2 = new int[arr.length];
for(int h = 0; h < arr.length - 1; h++){// makes arr2 all 0's
arr2[h] = 0;
}
arr2[arr2.length - 1] = arr[0];
for(int k = 0; k < arr.length; k++){
System.out.print(arr2[k] + ", ");
}
System.out.println();
while(arr2 != sorted){
for(int i = 1; i < arr2.length; i++){
if(arr[i] < arr2[arr2.length-1]){
int last = arr2[arr2.length-1];
int before = arr[i];
arr2[arr2.length-1]= before;
arr2[arr2.length-2]= last;
// CANT FIGURE OUT HOW TO SORT CORRECTLY
}
for(int k = 0; k < arr.length; k++){
System.out.print(arr2[k] + ", ");
}
System.out.println();
}
}
for(int k = 0; k < arr.length; k++){
System.out.print(arr2[k] + ", ");
}
}
public static void main(String[] args) {
int arr[] = {}; // Array that will be put into each sort method
//****************Multiple Arrays for testing*******************//
/* ************All Arrays Are Whole Numbers 1-100***************
arr1 = Array of size 20
*************************************************************** */
int arr1[] = {6,3,20,10,11,2,9,1,19,17,4,16,8,15,18,14,5,7,12,13}; // {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20}
//**************************************************************//
int arrayNumber = 1;
while(arrayNumber < 2){
if (arrayNumber == 1){
arr = arr1;
}
System.out.println("Array "+ arrayNumber +" Before Sorting");
for(int i = 0; i < arr.length; i++){
System.out.print(arr[i] + ", ");
}
System.out.println();
//************* Array put into Methods***************//
insertionSort(arr);
//***************************************************//
arrayNumber++; // Adds 1 to arrayNumber to show next array
}
}