【发布时间】:2022-01-20 00:48:19
【问题描述】:
我是编码新手,我按字母从最少到最多的顺序排列代码。请帮助我了解如何将代码按字母顺序排列。
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
String[] a = new String[] {"bread", "milk", "cheese", "spinach", "apple", "peanuts"};
System.out.println("Before Sort:" + Arrays.toString(a));
insertionSort(a);
System.out.println("After Sort: " + Arrays.toString(a));
System.out.println();
a = new String[] { "Allison", "Neha", "Charley", "Jason", "Tyson", "Miles", "Riley" };
System.out.println("Before Sort:" + Arrays.toString(a));
insertionSort(a);
System.out.println("After Sort: " + Arrays.toString(a));
}
public static void insertionSort(String[] a) {
// Move the marker from index 1 to the last index
for (int i = 1; i < a.length; i++) {
// Insert the element at the marker to the right position
insert(a, i);
}
}
public static void insert(String[] a, int marker) {
String unsortedElement = a[marker];
// shift other elements to the right to create the correct position
int correctPosition = marker;
for (int i = marker - 1; i >= 0; i--) {
if (a[i].length() > unsortedElement.length()) {
a[i + 1] = a[i];
correctPosition--;
}
else {
break; // stop looping
}
}
// Insert the unsorted element to the correct position
a[correctPosition] = unsortedElement;
}
}
【问题讨论】:
标签: java insertion-sort alphabetical