[英]What's the better way to write this function?
我必須遍歷一個數組並打印出它是否已排序,如果不是,則打印出未排序的前兩個元素(例如:6> 5)。
因此,我想知道使用函數執行此操作的最佳方法是什么:
void
函數,該函數打印出“已排序”或“未排序”,如果不是,則也打印出兩個元素。 boolean
函數,該函數打印出兩個未排序的元素(如果有的話),並最終返回true或false。 然后根據函數返回的內容,打印出數組是否在main
排序。 main
所有內容都可能不適合某個功能嗎? 請注意,我並不是在尋求有關作業本身的任何幫助!
我將創建一個返回最后排序的單元格索引的函數,因此,如果它是最后一個單元格,則將對所有內容進行排序,並且如果它小於您可以輕松找到下一個元素並在main中打印的話。 我不認為將函數用於其他目的時應該具有副作用(例如打印),並且可以使用這樣的返回索引的函數:
private int getFirstSortedIndex(int[] numbers){
int index = 0;
//find and return the first sorted index;
return index;
}
public static void main(String[] args){
int[] numbers;
//get the array from user input or arguments
int index = getFirstSortedElement(numbers);
if( index < numbers.length-1){
//print numbers[index] and numbers[index+1]
} else{
//print "it's sorted"
}
}
我將創建一個方法,該方法返回未正確排序的第一個元素的索引:
/**
* @param array ordered array
* @return the index of the first unordered element, or -1 if the array is ordered
*/
static int isOrdered(int[] array) {
// iterate through the array
// if a two sequential elements are not ordered, return the index of the first element
// if all is ok, return -1
}
然后執行:
int unsortedIndex = isOrdered(array);
if (unsortedIndex != -1) {
System.out.println(array[unsortedIndex] + ", " + array[unsortedIndex + 1]);
}
這比直接在isOrdered()
打印元素更好,因為現在您可以根據需要在代碼的其他部分重用isOrdered()
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.