[英]Recursively sorting an array of Strings without an auxiliary parameter
事實證明,我教授的一項任務對我來說特別棘手。 我必須編寫帶有以下標頭的方法:
public static void sort(String[] a)
該方法應按升序對數組進行排序(不確定這是否意味着“字符串長度的升序”,但這就是我所假設的)。
要點:不允許以任何方式更改方法標頭,不允許使用合並排序或快速排序,也不允許使用任何無關的包/庫。
合並排序和快速排序對我來說並不是什么大不了的事,因為我也不喜歡,但是我發現很難在不傳遞一些輔助參數的情況下做到這一點(存儲索引位置數組)將在遞歸調用中使用。
經過幾個小時的挫折,我基本上想出了這是我的想法:
public static void sort(String[] a)
{
String temp;
// Note that we use a.length - 1 in the loop condition
// to account for the fact that we will be checking the value of the
// element at the current index against the value of the element at the NEXT index.
// Since array indices are zero-based, iterating from 0 to a.length would result
// in an ArrayIndexOutOfBoundsException when we index = 7, since the
// base case would check a[7] against a[8], the latter of which does not exist
for (int index = 0; index < a.length - 1; index++)
{
if (a[index].length() < a[index + 1].length())
{
continue;
}
else
{
temp = a[index + 1];
a[index + 1] = a[index];
a[index] = temp;
// Recursive call to the sort method
sort(a);
}
}
}
基本思想是使用for循環“多次”檢查每個元素,以鼓勵每個元素進入其“適當位置”(按“遞增順序”的含義)。 我懷疑這是正確的,盡管我尚未對其進行測試(教授尚未為此任務上傳驅動程序)。
如果沒有,也許有人可以指出我正確的方向嗎? 在Array或String類中似乎沒有任何有用的方法。 我什至在這里看不到遞歸的用處。 如果我只是一次又一次地將相同的數組傳遞給方法,那會沒有用嗎?
該解決方案效率不高,因為它涉及創建新數組和復制,但是它滿足必須將遞歸與提供的方法簽名一起使用的要求。 它還滿足了不得使用合並排序和快速排序的要求。
import java.util.Arrays;
public class RecursiveInsertionSort {
public static void sort(String[] a)
{
if (a.length==1) {
return;
}
// Copy array from 1..length-1 into new array rest
String rest [] = Arrays.copyOfRange(a, 1, a.length);
// sort rest
sort(rest);
// insert a[0] into rest and store the result in a
insert(a,rest);
}
// insert a[0] into sort and store result in a
private static void insert(String [] a, String [] sorted) {
int i;
String saveFirst = a[0];
// Find index 'i' where such that sorted[i] > a[0]
for (i=0; i < sorted.length; i++) {
if (saveFirst.compareTo(sorted[i])<0) {
break;
}
}
// Copy elements less than a[0] from sorted to a
for (int j=0; j < i; j++) {
a[j] = sorted[j];
}
// insert a[0]
a[i] = saveFirst;
// copy elements greater than a[0] from sorted to a
for (int j=i+1; j < a.length; j++) {
a[j] = sorted[j-1];
}
}
public static void main(String args[]) {
String [] testData = {"Apples", "Oranges", "Cranberries", "Guava" };
sort(testData);
for (String s: testData) {
System.out.println(s);
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.