Remove Duplicates from unsorted array,它的错误在于9-10行k out of bound,改成下面这样就没问题了
public class removeDuplicates {
public static int[] remove(int[] arr){ int end = arr.length; for(int i = 0; i < end; i++){
for(int j = i + 1; j < end; j++){
if(arr[i] == arr[j]){
for(int k = j+1; k < end; k++){
arr[k-1] = arr[k];
}
end--;
j--;
}
}
} int[] whitelist = new int[end];
for(int i = 0; i < end; i++){
whitelist[i] = arr[i];
}
System.out.print("new length is ");
System.out.println(end);
return whitelist;
} public static void main(String[] args) {
int[] arr = {3, 2, 1, 3, 2, 1, 3, 2, 1};
remove(arr);
for(int i:arr){
System.out.print(i);
System.out.print(", ");
}
}
}
Selection Sort Ascending order, 它的错误在于7行大于小于错误
public static int[] doSelectionSort(int[] arr){ for (int i = 0; i < arr.length-1; i++)
{
int index = i;
for (int j = i + 1; j < arr.length; j++)
if (arr[j] < arr[index])
index = j; int smallerNumber = arr[index];
arr[index] = arr[i];
arr[i] = smallerNumber;
}
return arr;
}
Selection Sort Dscending order, 他的错误在于第5行大于小于错误
public static int[] doSelectionSort(int[] arr){
for (int i=0; i<arr.length-1; i++) {
int max = i;
for (int j=1; j<arr.length; j++) {
if (max < arr[j]) {
max = j;
}
}
if (max != i) {
int temp = arr[i];
arr[i] = arr[max];
arr[max] = temp;
}
}
return arr;
}
Reverse an int array, 它的问题在于第3行忘了-1
for (int i=0; i<arr.length/2; i++) {
int temp = arr[i];
arr[i] = arr[arr.length-1-i];
arr[arr.length-1-i] = temp; }
Print Pattern, 打印11, 1111, 111111,中间需要换行,它的问题在于括号少打了