[英]Printing where the last inserted array position
我想打印一個數組,該數組聲明“ placedPosition”或數組中參數的位置。 此位置是最新數字插入到數組排序部分中的位置。“ currPosition”與之相同,但是我可以弄清楚是否能獲得所放置位置的幫助。 “ i”是placedPosition,“ c”是“ currPosition”。 它看起來應該像這樣:
我真的不確定如何去做,這是到目前為止的代碼:
public static void displaySort(int[] items, int currPosition, int placedPosition) {
System.out.println("Iteration #"+currPosition);
String[][] arr = new String[currPosition][currPosition];
String i="i";
String c="c";
String ic="ic";
System.out.println(arr[placedPosition][placedPosition]=i);
System.out.println(arr[currPosition][currPosition]=c);
System.out.println(Arrays.toString(items));
}
排序:
public static void insertionSort(int[] items) {
int currentPosition; // the number of items sorted so far
int currentItem; // the value being inserted
int backwardMovingIndex; // used to find where the current value gets inserted.
//displaySort(items, 0, 0); // use this call to display the list before the first iteration (iteration 0)
for (currentPosition = 1; currentPosition < items.length; currentPosition++) // Start with 1 (not 0)
{
currentItem = items[currentPosition];
for (backwardMovingIndex = currentPosition - 1; (backwardMovingIndex >= 0) && (items[backwardMovingIndex] > currentItem); backwardMovingIndex--) // Larger values are moving up
{
items[backwardMovingIndex + 1] = items[backwardMovingIndex];
}
items[backwardMovingIndex + 1] = currentItem; // Put the current value in its proper location
displaySort(items, currentPosition, backwardMovingIndex + 1); // use this call to display the list for all other iterations
}
}
對於初學者,您需要確保數字以固定的位數打印出來,因此,而不是System.out.println(Arrays.toString(items));
嘗試使用類似的代碼
for (int item : items) {
System.out.printf("%5d", item);
}
System.out.println();
要在列中放置“ i”,請使用以下代碼
int i = 1;
for (int x = 0; x<items.length; x++) {
if (x == i) {
System.out.printf("%5s", "i");
}
else {
System.out.printf("%5s", "");
}
}
System.out.println();
關鍵字使用相同的值(在此示例中為5)作為格式說明符,用於控制循環所有分支中的列寬。 如果這些是任意整數,則可能需要使用更大的值,例如10。如果想花哨,可以通過查看最大絕對值的以10為底的對數來確定需要多寬的列。在數組中。 然后,您可以使用String.format("%"+n+"d", item)
將整數轉換為正好為n
字符的字符串。
要完成您的問題,請在if / else結構中添加更多分支以檢查(x == c)
和(i == c) && (x == i)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.