我无法实施insertionSort()
方法。
import java.util.Random;
import java.util.Arrays;
public class Lab6 {
static final int SIZE = 100;
static int[] values = new int[SIZE];
static void initValues() {
Random rand = new Random();
for(int i =0; i< SIZE;i++) {
values[i] = rand.nextInt(100);// limit to 100
}
}
static boolean isSorted() {
boolean sorted = true;
for(int i=0;i<SIZE-1;i++) {
if(values[i] > values[i+1]){
sorted = false;
}
}
return sorted;
}
static void swap(int index1, int index2) {
int temp = values[index1];
values[index1] = values[index2];
values[index2] = temp;
}
static void insertElement(int endIndex) {
// FILL IN CODE HERE
boolean finished = false;
int current = endIndex;
boolean moretoSearch = true;
while (moretoSearch && !finished){
if (values[current] < values[current-1]){
swap(current, current-1);
current--;
}
else
finished = true;
}
}
我也不确定这个方法&#34; insertElementBinary(int endIndex)&#34;正确实施;
static void insertElementBinary(int endIndex) {
//FILL IN CODE HERE FOR BINARY SEARCH INSERTIONSORT
boolean finished = false;
int current = endIndex;
boolean moretoSearch = true;
while (moretoSearch && !finished){
if (values[current] < values[current-1]){
swap(current, current-1);
current--;
moretoSearch = (current != endIndex);
}
else
finished = true;
}
}
这是我的主要问题所在:
static void insertionSort() {
//FILL IN CODE HERE
for (int i =0; i < SIZE; i++){
insertElement(i);
insertElementBinary(i);
}
}
其余的都很好:
public static void main(String[] args) {
Lab6.initValues(); // generate the random array
System.out.println(Arrays.toString(values));
System.out.println(isSorted());
insertionSort();
System.out.println(Arrays.toString(values));
System.out.println(isSorted());
}
}
答案 0 :(得分:0)
你非常接近正确。
在你的insertElement(int endIndex)方法中,你需要确保你的current > 0
,如下所示,否则你将有一个数组越界错误。
static void insertElement(int endIndex) {
boolean finished = false;
int current = endIndex;
boolean moretoSearch = true;
while (moretoSearch && !finished && current > 0){
if (values[current] < values[current-1]){
swap(current, current-1);
current--;
}
else
finished = true;
}
}
同样的修复适用于您的insertElementBinary(int endIndex)
方法。您可以通过在insertElement(i)
方法中注释insertElementBinary(i)
或insertionSort()
来测试两者。两者都可以正常工作。