因此,我必须设计一种无需使用Java API即可将quicksort用作排序算法的方法。然后,我必须编写另一个方法来返回排序后的数组,如果在其中找到了被搜索的元素,则使用二进制搜索返回true。我不知道我在哪里犯这个愚蠢的错误。
public class Aufgabe1 {
public static void sort(int[] array) {
/* TODO: add code here */
sort(array, 0, array.length - 1);
}
public static void sort(int[] array, int start, int end) {
int i = start;
int j = end;
int pivot = array[(start+end)/2];
while (i <= j) {
while (array[i] < pivot) {
i++;
}
while (pivot < array[j]) {
j--;
}
if (i <=j) {
int h = array[i];
array[i] = array[j];
array[j] = h;
i++;
j--;
}
}
if (start < i-1) {
sort(array, start, i - 1);
}
if (i < end) {
sort(array, i, end);
}
}
public static boolean binSearch(int[] array, int elem) {
/* TODO: add code here */
int i = 0; //the first element
int j = array.length -1; // the last element
while (i<=j) {
int k = i + ((i+j)/2); //try the middle word
if (elem == array[k]){
return true;
}
if (elem < array[k]) {
j = k-1;
return false;
}else {
i = k+1;
return false;
}
}
return false;
}
//just for testing
public static void main(String[] args) {
int[] arr = new int[] {5, 3, 7, 2, 1, 6};
sort(arr);
for(int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
binSearch(arr,5);
}
尝试此操作,修复了一些小错误,您在错误的位置放置了几个i和j。虽然,我建议您对代码进行一些模块化,因为这将使事情更易于阅读,并使您对正在发生的事情有更好的了解。请注意,您实际上并未返回正确的位置,因此除非元素位于中间,否则它将始终返回false。另外,不建议使用静态方法。
编辑:另外,我刚刚注意到您在结束课程的末尾缺少一个'}'。
public class Main
{
public static void sort(int[] array)
{
/* TODO: add code here */
sort(array, 0, array.length - 1);
}
public static void sort(int[] array, int start, int end)
{
int i = start;
int j = end;
int pivot = array[(start+end)/2];
while (i <= j)
{
while (array[i] < pivot)
{
i++;
}
while (pivot < array[j])
{
j--;
}
if (i <=j)
{
int h = array[i];
array[i] = array[j];
array[j] = h;
i++;
j--;
}
}
if (start < i-1)
{
sort(array, start, i - 1);
}
if (i < end)
{
sort(array, i, end);
}
}
public static boolean binSearch(int[] array, int elem)
{
/* TODO: add code here */
int i = 0; //the first element
int j = array.length -1; // the last element
int k = i + ((i+j)/2); //try the middle word
while (k >= 0 && k < array.length)
{
if (elem == array[k])
{
return true;
}
if (elem < array[k])
{
k--;
}
else
{
k++;
}
}
return false;
}
//just for testing
public static void main(String[] args)
{
int[] arr = new int[] {5, 3, 7, 2, 1, 6};
sort(arr);
for(int i = 0; i < arr.length; i++)
{
System.out.print(arr[i] + " ");
}
if (binSearch(arr,5))
{
System.out.println("TRUE");
}
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句